Skip to content
Advertisement

Merging an array property with the same key within an object

If I want to append to an existing property that’s an array, what’s the cleanest solution?

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"
}

It instead overwrites the index of access with the last assignment.

Answer

You can simplify logic

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

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