1

Hi how to append javascript objects to another one for example:

ObjectA = [
           {
            "id":"1",
            "name":"name 1"
           }
          ]

ObjectB = [
           {
            "id":"2",
            "name":"name 2"
           }
          ]

result would be like this:

Result = [
           {
            "id":"1",
            "name":"name 1"
           },
           {
            "id":"2",
            "name":"name 2"
           }
          ]

I tried to use Object.Assign() but it just overwrite the first object. Hope you can help me with this. Thanks!

CharybdeBE
  • 1,791
  • 1
  • 20
  • 35
asdfghmak
  • 33
  • 7
  • Possible duplicate of [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Amit Chigadani Aug 30 '18 at 07:37

3 Answers3

1

You can use Object.assign() with a 3rd object

ie:

let result = {}
Object.assign(result, ObjectA, ObjectB) 

With that method you dont modify ObjectA and ObjectB

Edit because your object are arrays :

  let result = ObjectA.concat(ObjectB)

concatdoes not modify the original objects

CharybdeBE
  • 1,791
  • 1
  • 20
  • 35
1
Manish Gharat
  • 400
  • 1
  • 10
1

Your Objects are inside an array. So you can use array.concat()

let ObjectA = [
           {
            "id":"1",
            "name":"name 1"
           }
          ]

let ObjectB = [
           {
            "id":"2",
            "name":"name 2"
           }
          ]
          
          
var result = ObjectA.concat(ObjectB);     

console.log(result);
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98