Dragomana

Destr_Array_of_Objects

May 29th, 2022 (edited)
704
336 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let cars = { Nissan: [{'Primera':2001}, {'Almera':2004}, {'Mikra':2003}],
  2.              Toyota: [{'Corolla':2011}, {'Carina':2000}, {'Avensis':2013}],
  3.                Lada: [{'Niva':1991}, {'Samara':1999}, {'jiguli':1989}]
  4. }
  5. // търсим Nissan
  6. if(cars.hasOwnProperty('Nissan')){
  7.     let nissanArr = cars['Nissan']  // nissanArr = [{'Primera': 2001},{'Almera':2004}, {...}]
  8. }
  9.  
  10. let carsArr = Object.entries(cars)
  11.  
  12. console.log(carsArr);   //[ [Nissan, [{},{},{}], [Toyota, [{},{},{}],..] ]
  13. console.log(carsArr[0]);  //[ Nissan, [{Primrera: 2001},{Almera: 2004},{...}] ]
  14.  
  15. console.log(carsArr[0][0]);   // Nissan
  16. console.log(carsArr[0][1]);   // [{Primrera: 2001},{Almera: 2004},{...}]
  17.  
  18. console.log(carsArr[1]);       //[ Toyota, [{'Corolla':2011}, {'Carina':2000}, {...}] ]
  19. console.log(carsArr[1][0]);    // Toyota
  20. console.log(carsArr[1][1]);    // [{'Corolla':2011}, {'Carina':2000}, {...}]
  21.  
  22.  let modelsArr = carsArr[1][1]
  23.  
  24. modelsArr.forEach( x=> {
  25.     let [name, year] = Object.entries(x)[0]
  26.     console.log(name, year);  // Corolla 2011
  27. })
  28.  
  29. // 1. извличане на Primera, 2001 с for in!!
  30. for(let car in cars){
  31.     console.log(car);
  32. cars[car].forEach(x =>{
  33.     let [name1, year1] = Object.entries(x)[0]
  34.  
  35. })
  36.     // console.log(cars[car]);
  37. }
RAW Paste Data Copied