首页 > 解决方案 > 在对象中合并具有相同键的数组属性

问题描述

如果我想附加到一个现有的数组属性,最干净的解决方案是什么?

function adminConditional(user) {
    return {
      ...user,
      priority: 1,
      access: ['system2']
  }
}

console.log(
  {
    ...(adminConditional)({name: "andrew", type: "Admin"}), // function name can vary
    access: ['system1'] // always set
  }
)

// Expected output:
{
  access: ["system1", "system2"],
  name: "andrew",
  priority: 1,
  type: "Admin"
}
// Actual output:
{
  access: ["system1"],
  name: "andrew",
  priority: 1,
  type: "Admin"
}

access相反,它会用最后一个赋值覆盖索引。

标签: javascript

解决方案


要使用扩展语法附加到数组,您可以使用以下语法:

let arr = [1,2,3];
let newArr = [...arr, 4];

newArr 将包含[1,2,3,4]. 同样可以在对象中应用,只需使用扩展运算符将属性引用到函数中,就可以获得相同的结果:

function adminConditional(user) {
    return {
      ...user,
      priority: 1,
      access: ['system2']
  }
}

console.log(
  {
    ...(adminConditional)({name: "andrew", type: "Admin"}),
    access: [...(adminConditional)({name: "andrew", type: "Admin"}).access, 'system1']
  }
)

推荐阅读