gpt4 book ai didi

javascript - 无法访问嵌套对象数组内的数据

转载 作者:行者123 更新时间:2023-12-01 00:36:32 24 4
gpt4 key购买 nike

我有一个对象数组,我想对其进行迭代并创建一个新的对象数组。

首先,我映射数据,然后循环访问每个对象以提取值。我想存储每个对象的位置名称和值。

我的代码返回空结果。我无法更改数据的声明方式。有人可以帮助我理解为什么我总是得到空结果吗?

[
{
"euValue": null,
"asValue": null
}
]

const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];

const formatData = () => {
let formattedData = [];
let euValue, asValue;

formattedData = data.map(location => {
for (const l in location) {
if (location.hasOwnProperty(l)) {
const _this = location[l];
euValue = _this.Location === "Europe" ? _this.Value : null;
asValue = _this.Location === "Asia" ? _this.Value : null;
}
}
return {
euValue,
asValue
};
});

return formattedData;
};

const newData = formatData();
console.log(newData);

编辑预期结果是

[
{
"euValue": “Ireland”,
"asValue": “China”
}
]

最佳答案

假设在 data 中,您可以有多个带有 Location 数组的对象,而这些对象只有 2 个对象(一个用于欧洲,另一个用于亚洲),您应该更改您的函数像这样的事情

    const data = [
{
Locations: [
{
Location: { Name: "Europe" },
Value: "Ireland"
},
{
Location: { Name: "Asia" },
Value: "China"
}
]
}
];
const formatData = () => {
// iterate all data objects
return data.map((topLocation) => {
const res = {};
// loop over Location children objects
topLocation.Locations.forEach((location) => {
const { Name } = location.Location;
// decide where to save Value base on the Location.name
if (Name === "Europe") {
res.euValue = location.Value;
} else if (Name === "Asia") {
res.asValue = location.Value;
}
});
return res;
});
};
const newData = formatData();
console.log(newData);

关于javascript - 无法访问嵌套对象数组内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58085889/

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