Search code examples
javascriptnode.jsarraysecmascript-6javascript-objects

Loop through an object and return the values of a specific property


I am trying to loop through an object and get the specific properties values, but I am only either getting the keys or the values. Here is what I am doing:

var fakeData = {
     "manufacturer": "tesla",
     "cars": [
          {"title": "CALI", "name": "CALI", "type": "string" },
          {"title": "TEXAS", "name": "TEXAS", "type": "string" },
          {"title": "NY", "name": "NY", "type": "string" }
     ],
     "usedCars": [
          {"title": "FL", "name": "FL", "type": "string" }
     ],
}

for (key in fakeData) {
 console.log(`${key}:${fakeData[key]}`)
}

I am trying to get the title of the cars property. I have tried doing ${key.cars}:${fakeData[key.cars]} but I get undefined. Any suggestions how to access that property? TIA


Solution

  • Do you mean something like this?

    var fakeData = {
         "manufacturer": "tesla",
         "cars": [
              {"title": "CALI", "name": "CALI", "type": "string" },
              {"title": "TEXAS", "name": "TEXAS", "type": "string" },
              {"title": "NY", "name": "NY", "type": "string" }
         ],
         "usedCars": [
              {"title": "FL", "name": "FL", "type": "string" },
         ],
    }
    
    // using map
    let carTitles = fakeData.cars.map(({title})=>title);
    
    console.log(carTitles);
    
    // using for loop
    
    let carTitles2=[];
    for ({title} of fakeData.cars)
      carTitles2.push(title);
    
    console.log(carTitles2);
    console.log('cars as string are:', carTitles2.join(','));
    
    // both cars and usedCars using one loop
    let cs  = '';
    let ucs = '';
    let clen=fakeData.cars.length;
    let uclen=fakeData.usedCars.length;
    let len=Math.max(clen,uclen);
    for (let i=0;i<len;i++) {
       if (clen>0 && i<clen)
         cs = cs + (i ? ',' : '') + fakeData.cars[i].title;
       if (uclen>0 && i<uclen)
         ucs = ucs + (i ? ',' : '') + fakeData.usedCars[i].title;
    }
    
    console.log('cars are:', cs);
    console.log('used cars are:', ucs);