繁体   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