繁体   English   中英

循环通过 object 并返回特定属性的值

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

我正在尝试遍历 object 并获取特定的属性值,但我只能获取键或值。 这是我正在做的事情:

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]}`)
}

我正在尝试获取汽车财产的所有权。 我试过做${key.cars}:${fakeData[key.cars]}但我没有定义。 任何建议如何访问该属性? TIA

你的意思是这样的吗?

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

这将遍历汽车 object 并记录汽车标题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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