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!

1

3 Answers 3

1
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

object.assign overwrites my first object
Yes but in the exemple i provide you we use a 3rd object instead of overwritting ObjectA; Anyway because you have array the concat soultion is more adapted
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);

4 Comments

Hi i use object in typescript so concat is useless
Your objects are not objects at the first place. They are arrays. And FYI, Array.concat works for typescript too. It is a super set of javascript.
yes but it gets an error, my object looks like this Object = [ {id:1,name:"name"}]
That's an array and not an Object. You may check Array.isArray(Object). It returns true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.