6

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?

4
  • 1
    Perhaps you're looking for Object.assign() Commented Aug 24, 2018 at 12:41
  • var obj = Object.assign(obj, loc) is the way out here. Commented Aug 24, 2018 at 12:41
  • you can also use merge from lodash, if you have that lib... lodash.com/docs/#merge Commented Aug 24, 2018 at 12:48
  • use like obj.leftArray=[]; which automatically generate new obj. Commented Aug 24, 2018 at 12:53

2 Answers 2

7

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.

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

3 Comments

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 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.
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!
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.