5

I have 2 objects, and I need to add one object to the other object.

var loc = {
  leftArray: [],
  topArray: [],
  bottomArray: [],
  rightArray: []
}

var obj = {
  id: "ce",
  icon: "logo/image.png",
  name: "CE",
  type: "type2",
  version: 3.4
}
var obj = {
  id: "ce",
  icon: "logo/image.png",
  name: "CE",
  type: "type2",
  version: 3.4,
  leftArray: [],
  topArray: [],
  bottomArray: [],
  rightArray: []
}

Is there any simple way to do this?

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
girish
  • 203
  • 1
  • 4
  • 14

2 Answers2

6

You can do it with Object.assign();

obj = Object.assign(obj, loc);

or just

Object.assign(obj, loc);

as T.J. Crowder proposed in his comment.

  • Just FWIW, there's no need for the assignment in this case, just `Object.assign(obj, loc);` would be sufficient. (And you certainly wouldn't want the `var`, since `obj` is already declared.) – T.J. Crowder Aug 24 '18 at 13:07
  • @T.J.Crowder Yeah, you're right about not redeclaring the variable. I didn't know that you don't need to assign the result of Object.assign(). Thanks for the info. I edited my answer accordingly. –  Aug 24 '18 at 14:25
  • `Object.assign` returns the first object you pass in. That's so you can pass in an object initializer ("literal"), like this: `const foo = Object.assign({}, something, blah);` That's just a one-liner version of `const foo = {}; Object.assign(foo, something);` Thanks for contributing, and welcome! – T.J. Crowder Aug 24 '18 at 14:32
2

you can merge them using Spread syntax like

let objOne = { a: 'hi' }
let objTwo = { b: 'hello' }
let objOneAndTwo = { ...objOne, ...objTwo }; // { a: 'hi', b: 'hello' }

or by using Object assign:

let objOneAndTwo = Object.assign({}, a, b)

note that using this way if your objects would have properties with the same name priority will be with the most right object (in this example objectTwo)

additional info:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Amir Ghezelbash
  • 2,195
  • 15
  • 24