首页 > 解决方案 > 无法访问嵌套对象数组中的数据

问题描述

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

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

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

[
  {
    "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”
  }
]

标签: javascriptarraysobject

解决方案


你错过了第二个循环,你也覆盖了usValueandeuValue并且你最好使用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))


推荐阅读