Anton
Anton

Reputation: 1502

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

How to merge two objects together. And add new object into body every time when number is matched? I tried spread operator but it was overwriting the value instead of changing it.

Before:

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

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

I need to merge them to have:

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

Upvotes: 0

Views: 68

Answers (2)

iatsi
iatsi

Reputation: 151

If there are just two objects, you could do it like this

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

Upvotes: 0

brk
brk

Reputation: 50291

Just check if the number key is equal in both case then iterate obj2.body and push each item in obj.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)

Upvotes: 1

Related Questions