簡體   English   中英

在 object 中合並具有相同鍵的數組屬性

[英]Merging an array property with the same key within an object

如果我想將 append 轉換為現有的數組屬性,最干凈的解決方案是什么?

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索引。

要使用擴展語法將 append 轉換為數組,您可以使用以下語法:

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

newArr 將包含[1,2,3,4] 同樣可以在 object 中應用,只需使用擴展運算符將屬性引用到 function 中,您就可以獲得相同的結果:

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

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

您可能希望避免在access中出現重復,並避免調用 function 兩次,因此沒有捷徑可以做到這一點。 我會建議:

 function adminConditional(user) { return {...user, priority: 1, access: ['system2'] } } let user = adminConditional({name: "andrew", type: "Admin"}); console.log( {...user, access: [...new Set(['system1', ...user.access])] } )

你可以簡化邏輯

 function adminConditional(user) { return {...user, priority: 1, access: ['system2', ...user.access] }; } console.log( {...(adminConditional)({ name: "andrew", type: "Admin", access: ['system1'] }) } )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM