如何解决循环遍历对象并返回特定属性的值
我试图遍历一个对象并获取特定的属性值,但我只是获取键或值。这是我在做什么:
var fakeData = {
"manufacturer": "tesla","cars": [
{"title": "CALI","name": "CALI","type": "string" },{"title": "TEXAS","name": "TEXAS",{"title": "NY","name": "NY","type": "string" }
],"usedCars": [
{"title": "FL","name": "FL",}
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",{"title": "NY","name": "NY","type": "string" }
],"usedCars": [
{"title": "FL","name": "FL",],}
// 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);
这将遍历汽车对象并记录汽车标题。
var fakeData = {
"manufacturer": "tesla",}
let result = ''
for (car of fakeData.cars) {
result += `The new cars are in ${car.title}\n`;
}
console.log(result);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。