簡體   English   中英

如何根據條件合並對象的數組屬性?

[英]How to merge the array property of an object based on a condition?

如何將兩個對象合並在一起。 並在每次數字匹配時將新對象添加到正文中? 我嘗試了傳播算子,但它覆蓋了值而不是更改它。

之前:

let obj = {
  number: "123",
  body:[
    {
      id:'client',
      text:'hi'
    }
  ]
}

let obj2 = {
  number: "123",
  body:[
    {
      id:'client',
      text:'Hello there'
    }
  ]
}

我需要將它們合並為:

obj = {
  number: "123",
  body:[
    {
      id:'client',
      text:'hi'
    },
    {
      id:'client',
      text:'Hello there'
    }
  ]
}

只需檢查number鍵在兩種情況下是否相等,然后迭代obj2.body並將其推入obj.bodyobj.body

 let obj = { number: "123", body: [{ id: 'client', text: 'hi' }] } let obj2 = { number: "123", body: [{ id: 'client', text: 'Hello there' }] } if (obj2.number === obj.number) { obj2.body.forEach(item => { obj.body.push(item) }) } console.log(obj) 

如果只有兩個對象,您可以這樣做

if (obj.number == obj2.number) {
   obj.body = obj.body.concat(obj2.body)
   console.log("Here's is your new object", obj);
} 

暫無
暫無

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

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