0

I am new to JS and I am trying to do a basic operation on a JS object.

I have the following object:

var originalObj = {
   id: 1,
   name: 'originalObj'
}

Now I would like to add another object as a field to originalObj.

var newObj = {
   newId: 2,
   name: 'newObj'
}

So expected outcome is:

orginalObj = {
  id: 1,
  name: 'originalObj',
  newObj: {
    newId: 2,
    name: 'newObj'
  }
}

What I tried so far:

  1. originalObj.newObj = newObj and originalObj['newObj'] = newObj

This results in:

orginalObj = {
      id: 1,
      name: 'originalObj',
      newObj: 
    }  
  1. Object.assign(originalObj, newObj) This add all the fields of newObj on the same level as originalObj. Like below:

    originalObj = { id: 1, name: 'originalObj', newId: 2, name: 'newObj' }

4
  • Object.assign(originalObj, {newObj}) Commented Apr 5, 2019 at 5:48
  • What is the difference between expected output and what you get from the first attempt? Commented Apr 5, 2019 at 5:55
  • @adiga I fixed my question sorry. Commented Apr 5, 2019 at 5:56
  • First attempt will give the proper output. Commented Apr 5, 2019 at 6:00

3 Answers 3

1

Depends on if you want a deep copy or just a reference.

originalObj.newObj = newObj; will assign a reference to newObj where as

originalObj.newObj = Object.assign({}, newObj); will create a new one.

Note: if your using ECMAScript 2015 (6th Edition, ECMA-262) you can use the spread operator ...

originalObj.newObj = {...newObj};

Example: https://jsbin.com/yisiyip/edit?js,console

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

Comments

0

originalObj.newObj=newObj; //this should do the job

in console it looks like this

Comments

0
const originalObj = {
   id: 1,
   name: 'originalObj'
}

const newObj = {
   newId: 2,
   name: 'newObj'
}

originalObj  = { ...originalObj, newObj }

what's happening here is you are spreading the values of originalObj into an empty object together with the value of newObj by shorthand method

reference:

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

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

1 Comment

Please explain answer in deatails to understand to others more effectively.

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.