【问题标题】:Changing the keys of a nested object in an Array with JavaScript使用 JavaScript 更改数组中嵌套对象的键
【发布时间】:2021-11-28 13:40:09
【问题描述】:

我需要更改对象的键。我可以使用 map 函数来更改外部对象的键。问题是,我怎样才能访问数组中的内部对象。在下面的代码中,我需要将team 键更改为teamName。我的结构必须是相同的顺序。

let myArray = [
  {
    id: 1,
    name: "foo",
    Organization: [{ team: "value1" }, { location: "value2" }],
  },
  {
    id: 2,
    name: "foo",
    Organization: [{ team: "value1" }, { location: "value2" }],
  },
];

如果我想将id 更改为userId,我可以像这样更改外部数组的键。

const newArray = myArray.map((item) => {
  return {
    userId: item.id,
  };
});

但是尝试更改 Organization 的内部对象列表中的键成为一个问题。修改内键的最佳方法是什么?

【问题讨论】:

  • 你试过什么?尝试后会发生什么?
  • “内部”和“外部”数组之间没有区别。数组就是数组。

标签: javascript nested-loops


【解决方案1】:

选项 1 - lodash mapKeys

import { mapKeys } from 'lodash';

const newArray = myArray.map(item => ({
  ...item,
  Organization: item.Organization.map(org =>
    mapKeys(org, (_, key) => (key === 'team' ? 'teamName' : key))
  ),
}));

选项 2 - 对象销毁

只要team 存在,您就可以破坏每个Organization 并使用teamName 重建它。

const newArray = myArray.map(item => ({
  ...item,
  Organization: item.Organization.map(({ team, ...rest }) =>
    Object.assign(rest, team ? { teamName: team } : {})
  ),
}));

结果

[
  {
    id: 1,
    name: 'foo',
    Organization: [{ teamName: 'value1' }, { location: 'value2' }],
  },
  {
    id: 2,
    name: 'foo',
    Organization: [{ teamName: 'value1' }, { location: 'value2' }],
  },
];

【讨论】:

    【解决方案2】:

    如果Organization 始终是一个包含 2 个元素的数组。其中第一个元素是属性为team 的对象,第二个元素是属性为location 的对象。然后下面的代码就可以了。

    let myArray = [{
      "id": 1,
      "name": "foo",
      "Organization": [{"team": "value1"}, {"location": "value2"}]
    }, {
      "id": 2,
      "name": "foo",
      "Organization": [{"team": "value1"}, {"location": "value2"}]
    }];
    
    const result = myArray.map((item) => {
      const [{ team: teamName }, location] = item.Organization;
      return { ...item, Organization: [{ teamName }, location] };
    });
    
    console.log(result);

    此答案使用destructuring assignment。如果您不知道这是什么,我强烈建议您查看链接文档。

    【讨论】:

      【解决方案3】:

      再简单不过了。

      console.log(
        [{
            "id": 1,
            "name": "foo",
            "Organization": [{
              "team": "value1"
            }, {
              "location": "value2"
            }]
          },
          {
            "id": 2,
            "name": "foo",
            "Organization": [{
              "team": "value1"
            }, {
              "location": "value2"
            }]
          },
        ].reduce((a, b) => {
          b.Organization[0] = {
            teamName: b.Organization[0].team
          }
          a.push(b)
          return a
        }, [])
      )

      【讨论】:

        猜你喜欢
        • 2021-02-12
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 2020-11-19
        • 2017-11-19
        • 2021-10-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多