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?

j08691
  • 204,283
  • 31
  • 260
  • 272
slinkhi
  • 947
  • 4
  • 16
  • 32
  • 1
    For the dupe: you'll want the second answer – Cerbrus Jul 15 '15 at 14:21
  • 1
    See also http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object-literal – j08691 Jul 15 '15 at 14:23
  • FYI I found this [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/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! – slinkhi Jul 16 '15 at 14:10
  • 2
    Actually I just found the [assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/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. – slinkhi Jul 16 '15 at 14:43

1 Answers1

0
// in React Js

let object1 = {
            prop1 : "a",
            prop2 : "b",
            prop3 : "c",
        };
        let object2 = {
            prop4 : "d",
            prop5 : "e",
            prop6 : "f",
        };
        let newObj = { ...object1, ...object2 };
fatemeh kazemi
  • 516
  • 6
  • 10
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53