add one object to another object in javascript

Viewed 4997

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?

2 Answers

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.

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

Related