clint_milner
clint_milner

Reputation: 365

How to combine two objects that have the same key and keep both values of that key

I have two objects:

{ query="twitter.com",  tags="dog" }

and

{ tags="funny" }

My ideal merge output would be:

{ query="twitter.com",  tags="dog,funny" }

I've looked at the Underscore/jQuery extend methods and they just seem to replace 'dog' with 'funny' rather than combining the two.

Does anyone have any suggestions?

Thanks!

Upvotes: 0

Views: 2973

Answers (4)

Pedro Vaz
Pedro Vaz

Reputation: 820

You could use map

Here is the snippet:

_.map(arr, function(val, key){
    if(arr1[key] != undefined) arr[key] = val  + "," + arr1[key];
});

Upvotes: 1

Mohan
Mohan

Reputation: 4829

Try this :

var obj1 = { query:"twitter.com",  tags:"dog" } ,obj2 = { tags:"funny" };

$.each(obj1, function(key,val){
    if(typeof obj2[key] != 'undefined') 
        obj1[key] = val + ',' + obj2[key];
});

alert(JSON.stringify(obj1))

Upvotes: 0

Muhammad Usman
Muhammad Usman

Reputation: 1362

By using .each function we can do something that you want try this code

var arr= { query:"twitter.com",  tags:"dog" };
var arr1 = { tags:"funny" };

$.each(arr, function(key, val){

    if(arr1[key] != undefined)
    {
        arr1[key] = arr1[key]  + "," + val;
    }
    else
    {
        arr1[key] = val;
    }
});

console.log(arr1);

Running Code available on JSFIDDLE

Upvotes: 0

MoLow
MoLow

Reputation: 3084

here you go:

this will work for as many objects as you need to combine: `combine(data1, data2, ...., dataN)

var data1 = {query:"twitter.com", tags: "dog"};
var data2 = {tags: "funny" }

var combine = function() {
   var obj = {};
   for(var i in arguments){
     var curr = arguments[i];
     for(var key in curr){
       if(!obj[key]) obj[key] = [];
       obj[key].push(curr[key]);
     }
   }
  
  var __obj={};
  for(var key in obj)
    __obj[key] = obj[key].join(",");
  
  return __obj;
}  

document.write(JSON.stringify(combine(data1, data2)));

Upvotes: 0

Related Questions