Append objects in ES6?

Manoj Yadav picture Manoj Yadav · Jan 4, 2019 · Viewed 7.3k times · Source

In my react native app, i stored an object locally and retrieved it, worked fine but now i wanted to append an another object to previous object, like i have two objects:

    const obj1 = {key1: keyone, key2: keytwo}
    const obj2 = {key4: keyfour, key6: keysix}

All i want back is an object as

    { key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }

and im trying to do it as:

    const newVal = `${obj1}, ${obj2}`

which returns "object Object"

I went through Object.assign() and also through lodash's .merge() functionality but it seems to be they are merging common fields in object.

How do i acheive this?

Answer

Piyush Zalani picture Piyush Zalani · Jan 4, 2019

1. If you want to have an array of objects then you can use this approach:

const arr = [obj1, obj2];

it will provide you with the following result:

[{ key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }] 

2. If you want to have the object of objects then you can try this:

const arr = {obj1, obj2};

this lead to following result:

{ obj1: { key1: keyone, key2: keytwo }, obj2: { key4: keyfour, key6: keysix }} 

3. If you want a single object you can try this:

const arr = {...obj1, ...obj2};

will produce the following result:

 { key1: keyone, key2: keytwo, key4: keyfour, key6: keysix }