0

I have two object like below

var data = {
        site_name: "my_site",
        page_id: "page_name",
        city: "New York",
        region_code: "NY",
        country_code: "US"
     },
     user_data = {
        user: "user_name",
        conversion_rate: 1.25
     };

I want to concatenate these two object like below

user_data = {
     user: "user_name",
     conversion_rate: 1.25,
     site_name: "my_site",
     page_id: "page_name",
     city: "New York",
     region_code: "NY",
     country_code: "US"
 };

I did it by looping on second on by checking typeof user_data.key .... and it solved my problem but my curiosity is to do it without looping in an optimized way. Any of your suggestion will be appreciated.

Janie
  • 638
  • 9
  • 26
  • i think jquery's extend( target [, object1 ] [, objectN ] ) is a good option – Sunny Soni Jul 21 '16 at 09:37
  • Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – insan-e Jul 21 '16 at 09:37

3 Answers3

3

You can use Object.assign of ES6:

var combined = Object.assign({}, data, user_data);

Or even:

Object.assign(user_data, data); // this will change `user_data`
str
  • 42,689
  • 17
  • 109
  • 127
1

If you can use Babel, simply use spread operator on objects:

var data = {
   site_name: "my_site",
   page_id: "page_name",
   city: "New York",
   region_code: "NY",
   country_code: "US"
},
user_data = {
   user: "user_name",
   conversion_rate: 1.25
};

var combined = {
  ...data,
  ...user_data
};

console.log(combined);

Please see the demo.

"Spread properties" is still in proposal stage 2, but you can use it with Babel.
See here more details about this feature.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
-1

This would work in your example case on all browsers:

data=JSON.stringify(data);
user_data=JSON.stringify(user_data);
user_data=user_data.replace("}",data.replace("{",","));
user_data=JSON.parse(user_data);
grateful
  • 1,128
  • 13
  • 25