簡體   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