【问题标题】:How to merge Array Key value from another Key in JavaScript如何从 JavaScript 中的另一个键合并数组键值
【发布时间】:2020-06-06 18:49:44
【问题描述】:
[
    0: {employeeId: "2", name: "chandan", email: "chandan@gmail.com"}
    1: {gender: "male"}
]

我想要这样的数组:

[
  0: {employeeId: "2", name: "chandan", email: "chandan@gmail.com", gender: "male"}
]

【问题讨论】:

    标签: javascript arrays json reactjs object


    【解决方案1】:

    您可以使用扩展运算符创建一个新对象,该对象将复制两个现有对象的属性。

    arr[0]={...arr[0],...arr[1]};
    

    【讨论】:

    • 数组长度不是静态的,所以我不能使用静态 [0] 键是动态的,如果您建议具有动态值的代码会很有帮助;
    • 所以你的数组有多个值?不止一个?
    • Józef Podlecki 的回答允许使用非静态数组长度。
    【解决方案2】:

    array.reduce和传播可以帮助你

    const arr = [{
        employeeId: "2",
        name: "chandan",
        email: "chandan@gmail.com"
      },
      {
        gender: "male"
      }
    ]
    
    const result = arr.reduce((acc, obj) => ({
      ...acc,
      ...obj
    }), {});
    
    console.log(result);

    --编辑

    Object.assign 风味(虽然在 chrome 83 上似乎慢了 1%)

    const arr = [{
        employeeId: "2",
        name: "chandan",
        email: "chandan@gmail.com"
      },
      {
        gender: "male"
      }
    ]
    
    const result = arr.reduce((acc, obj) => Object.assign(acc, obj), {});
    
    console.log(result);

    【讨论】:

    • 无论数组中有多少元素,这都会动态执行。它循环遍历数组,一遍又一遍地传播结果。
    • 现在我想知道Object.assign 是否是一个不错的选择。必须对 jsperf 进行一些测试
    • 添加了带有 object.assign 的变体
    • @JózefPodlecki spread 和 Object.assign 有什么区别?
    【解决方案3】:

    使用没有初始值的reduce 将聚合。

    const arr = [
      {
        employeeId: "2",
        name: "chandan",
        email: "chandan@gmail.com",
      },
      {
        gender: "male",
      },
    ];
    
    const output = arr.reduce((acc, curr) => Object.assign(acc, curr));
    
    console.log(output);

    【讨论】:

      【解决方案4】:

      你也可以通过映射它然后使用fromEntries来做到这一点:

      var data=[ {employeeId: "2", name: "chandan", email: "chandan@gmail.com"}, {gender: "male"}];
      
      var result = Object.fromEntries(data.flatMap(k=>Object.entries(k)));
      
      console.log(result);

      【讨论】:

        猜你喜欢
        • 2018-06-17
        • 1970-01-01
        • 2015-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        • 2017-10-27
        • 2015-03-31
        相关资源
        最近更新 更多