简体   繁体   中英

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

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);

This will loop through cars object and logs the car titles.

 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" } ], } let result = '' for (car of fakeData.cars) { result += `The new cars are in ${car.title}\n`; } console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM