javascript - 无法访问嵌套对象数组中的数据
问题描述
我有一个对象数组,我想对其进行迭代并创建一个新的对象数组。
首先,我映射数据,然后遍历每个对象以提取值。我想存储每个对象的位置名称和值。
我的代码返回空结果。我无法更改声明数据的方式。有人可以帮我理解为什么我一直得到空结果吗?
[
{
"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”
}
]
解决方案
你错过了第二个循环,你也覆盖了usValue
andeuValue
并且你最好使用forEach
而不是map
在这种情况下。
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = (data) => {
let formattedData = [],
values = {};
data.forEach(location => {
for (const l in location) {
if (location.hasOwnProperty(l)) {
const _this = location[l];
_this.forEach(el => {
if (el.Location.Name === "Europe") {
values["euValue"] = el.Value || null
}
if (el.Location.Name === "Asia") {
values["asValue"] = el.Value || null
}
})
}
}
});
formattedData.push(values)
return formattedData;
};
console.log(formatData(data))
推荐阅读
- javascript - 当我将变量用于选择器时,该事件不会触发
- python - Pandas read_csv():列包含数据框,但被读取为字符串
- android - 停止安卓导航栏
- php - 如何在 Laravel 中为自定义注册表单设置自定义自动登录
- javascript - 另一个窗口的Javascript关闭模式
- javascript - 在 Google Analytics 可跟踪点击后显示 mailto 链接
- r - 在 R 中创建一个带有 X 试验、Y 代表和 Z 图的 data.table
- html - 如何将输入表单结果集成到 R 块中?
- node.js - 每次创建文章并将其保存在数据库中时,如何生成 slug?
- firebase - 在 Heroku 上部署 Spring Boot 应用程序不工作