[英]How to iterate index in Javascript using forEach loop
我正在嘗試迭代這個對象。 我檢查了互聯網上的代碼,發現 Object.enteries 可以工作,但到目前為止它只返回第一個 CustomerName,即“Asad”。 我想將它迭代到完整的數組,而不僅僅是第一個。
var myObject = {
"records": [
{
"id": "recDBqsW7C3Dk3HMd",
"fields": {
"Latitude": "24.898907",
"Longitude": "67.117303",
"CustomerName": "Asad"
},
"createdTime": "2020-10-07T04:43:31.000Z"
},
{
"id": "recGlfTbUcEvP46Lf",
"fields": {
"Latitude": "24.907641",
"Longitude": "67.1088035",
"CustomerName": "Umar"
},
"createdTime": "2020-10-07T04:44:11.000Z"
},
{
"id": "recfsQsoznDyWPDe8",
"fields": {
"Latitude": "24.911112",
"Longitude": "67.105117",
"CustomerName": "Ali"
},
"createdTime": "2020-10-06T09:11:05.000Z"
}
]
};
Object.entries(myObject).forEach(([key, value], index) => {
console.log( value[index].fields.CustomerName); // key ,value
});
結果:
"Asad"
該數組實際上是您定義它的對象字面量的一個屬性。您需要做的就是訪問該數組並對其調用Array.prototype.forEach
以訪問它的元素。 像這樣的東西:
//Extract the array from your data structure into a variable. Always use //a const if the variable will not need to be re-assigned in the program. const { records } = { "records": [{ "id": "recDBqsW7C3Dk3HMd", "fields": { "Latitude": "24.898907", "Longitude": "67.117303", "CustomerName": "Asad" }, "createdTime": "2020-10-07T04:43:31.000Z" }, { "id": "recGlfTbUcEvP46Lf", "fields": { "Latitude": "24.907641", "Longitude": "67.1088035", "CustomerName": "Umar" }, "createdTime": "2020-10-07T04:44:11.000Z" }, { "id": "recfsQsoznDyWPDe8", "fields": { "Latitude": "24.911112", "Longitude": "67.105117", "CustomerName": "Ali" }, "createdTime": "2020-10-06T09:11:05.000Z" } ] }; //Iterate over the items in the array to access the data you need records.forEach(record => { console.log(`${record.id} = ${record.fields.CustomerName}`); });
通常,您在這里使用了錯誤的方法。
你需要做的是:
var myObject = { "records": [ { "id": "recDBqsW7C3Dk3HMd", "fields": { "Latitude": "24.898907", "Longitude": "67.117303", "CustomerName": "Asad" }, "createdTime": "2020-10-07T04:43:31.000Z" }, { "id": "recGlfTbUcEvP46Lf", "fields": { "Latitude": "24.907641", "Longitude": "67.1088035", "CustomerName": "Umar" }, "createdTime": "2020-10-07T04:44:11.000Z" }, { "id": "recfsQsoznDyWPDe8", "fields": { "Latitude": "24.911112", "Longitude": "67.105117", "CustomerName": "Ali" }, "createdTime": "2020-10-06T09:11:05.000Z" } ] }; myObject.records.forEach((value, index) => { console.log( value.fields.CustomerName); // key ,value });
通過這樣做,您將輕松地遍歷您的記錄並獲得所有名稱。
您當前正在做的是遍歷myObject
的鍵值對,其中Object.entries(myObject)
將返回給您[['records', [array of the users]]]
然后是forEach
塊中的console.log
將被調用一次,因為那里只有一個條目。
請試試這個代碼。 它找到keys
,然后用forEach
迭代
for (var key of Object.keys(myObject)) {
myObject[key].forEach((v) => {
console.log(v.fields.CustomerName)
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.