2

I have the following:

var x = {
  'a' : 1,
  'b' : 2
}

Then, I want to add the following to the object (my pseudocode):

x += {
  'c' : 3,
  'd' : 4
}

This obviously doesn't work as expected.. I basically end up with a "[Object][Object]" string. But what I really want is this:

var x = {
  'a' : 1,
  'b' : 2,
  'c' : 3,
  'd' : 4
}

I feel like there should be some sort of built-in operator or easy way to do this, other than just individually adding the properties or using a loop. But maybe I am wrong. Thoughts?

4
  • 1
    For the dupe: you'll want the second answer Commented Jul 15, 2015 at 14:21
  • 1
    See also stackoverflow.com/questions/1168807/… Commented Jul 15, 2015 at 14:23
  • FYI I found this spread operator which is exactly what I'm looking for, but it's for arrays not objects. I can't see that there is an object equivalent. Also it's EM6. But just putting more clarity into what I was looking for. I guess the long story short is it's simply not doable at this time. Thanks for links! Commented Jul 16, 2015 at 14:10
  • 2
    Actually I just found the assign method which is what I was hoping/looking for, though it too is EM6. Which in retrospect was in one of the answers on the link @Cerbrus posted. doh. Commented Jul 16, 2015 at 14:43

1 Answer 1

0
// in React Js

let object1 = {
            prop1 : "a",
            prop2 : "b",
            prop3 : "c",
        };
        let object2 = {
            prop4 : "d",
            prop5 : "e",
            prop6 : "f",
        };
        let newObj = { ...object1, ...object2 };
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I know I can do this. I was looking for a way to not have to do this.
It's not at the same time I think

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.