gpt4 book ai didi

javascript - 如何使用 forEach 循环在 Javascript 中迭代索引

转载 作者:行者123 更新时间:2023-12-04 08:36:28 24 4
gpt4 key购买 nike

我正在尝试迭代这个对象。我已经通过互联网检查了代码,发现 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}`);
});

关于javascript - 如何使用 forEach 循环在 Javascript 中迭代索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64774108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com