8

I need to merge two json object based on key value using javascript.

I have two different variable g and c.

terms: All values need to merge.

var g = [ { id: 36, name: 'AAA', goal: 'yes' },
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 57, name: 'CCC', goal: 'yes' },
    { id: 4, name: 'DDD', goal: 'yes' },
    { id: 39, name: 'EEE', goal: 'yes' },
    { id: 37, name: 'FFF', goal: 'yes' },
    { id: 59, name: 'GGG', goal: 'yes' },
    { id: 50, name: 'III', goal: 'yes' },
    { id: 43, name: 'HHH', goal: 'yes' },
    { id: 35, name: 'JJJ', goal: 'yes' } ]


 var c = [ { id: 36, name: 'AAA', circle: 'yes' },
    { id: 40, name: 'BBB', circle: 'yes' },
    { id: 57, name: 'CCC', circle: 'yes' },
    { id: 42, name: 'ZZZ', circle: 'yes' },
    { id: 4, name: 'DDD', circle: 'yes' },
    { id: 39, name: 'EEE', circle: 'yes' },
    { id: 37, name: 'FFF', circle: 'yes' },
    { id: 59, name: 'GGG', circle: 'yes' },
    { id: 43, name: 'HHH', circle: 'yes' },
    { id: 35, name: 'JJJ', circle: 'yes' },
    { id: 100, name: 'JJJ', circle: 'yes' } ]

I tried the following code: but i merge what are have same id in 'c' variable. but i need to merge compare 'g' and 'c'.

   var arrayList = [];
    for(var i in g) {
        var getid = g[i].id;
        var getname = g[i].name;
        var getgoal = g[i].goal;
        for(var j in c){
            var compareid = c[j].id;
            if(getid == compareid){
                var obj = {};
                obj.id = getid;
                obj.name = getname;
                obj.goal =  'yes';
                obj.circle = 'yes';
                console.log(obj);
                arrayList.push(obj);
            }
         }

    }
    console.log(arrayList);

Expected output:

[ { id: 36, name: 'AAA', goal: 'yes',circle: 'yes' },
    { id: 40, name: 'BBB', goal: 'yes',circle: 'yes' },
    { id: 57, name: 'CCC', goal: 'yes',circle: 'yes' },
    { id: 4, name: 'DDD', goal: 'yes' ,circle: 'yes' },
    { id: 39, name: 'EEE', goal: 'yes' ,circle: 'yes' },
    { id: 37, name: 'FFF', goal: 'yes' ,circle: 'yes'},
    { id: 59, name: 'GGG', goal: 'yes' ,circle: 'yes'},
    { id: 50, name: 'III', goal: 'yes' ,circle: 'no'},
    { id: 43, name: 'HHH', goal: 'yes' ,circle: 'yes'},
    { id: 35, name: 'JJJ', goal: 'yes' ,circle: 'yes'} ,
    { id: 42, name: 'ZZZ', goal: 'no' , circle: 'yes' },
    { id: 100, name: 'JJJ',goal: 'no' , circle: 'yes' }]
5
  • What is the problem doing this and what is the question? So far all you've stated is what you want to do ... not what you've done to try to do it Commented May 7, 2015 at 6:39
  • sorry i forgot to add my code. Commented May 7, 2015 at 7:03
  • Need to use only javascript not jquery. Commented May 7, 2015 at 7:21
  • what is your expected result in this case var g = [ { id: 36, name: 'AAA', goal: 'yes' },....] var c = [ { id: 36, name: 'foo', circle: 'yes' },.....] ?? Commented May 7, 2015 at 7:30
  • what is expected if two objects have same ids but different names? Commented May 7, 2015 at 8:08

4 Answers 4

6

You forgot to push obj in the first loop in case the id doesn't exist in c and to loop through c in case one or more id's of that object does not exist in g.

var g = [
        { id: 36, name: 'AAA', goal: 'yes' },
        { id: 40, name: 'BBB', goal: 'yes' },
        { id: 57, name: 'CCC', goal: 'yes' },
        { id: 4, name: 'DDD', goal: 'yes' },
        { id: 39, name: 'EEE', goal: 'yes' },
        { id: 37, name: 'FFF', goal: 'yes' },
        { id: 59, name: 'GGG', goal: 'yes' },
        { id: 50, name: 'III', goal: 'yes' },
        { id: 43, name: 'HHH', goal: 'yes' },
        { id: 35, name: 'JJJ', goal: 'yes' }
    ],
    c = [
        { id: 36, name: 'AAA', circle: 'yes' },
        { id: 40, name: 'BBB', circle: 'yes' },
        { id: 57, name: 'CCC', circle: 'yes' },
        { id: 42, name: 'ZZZ', circle: 'yes' },
        { id: 4, name: 'DDD', circle: 'yes' },
        { id: 39, name: 'EEE', circle: 'yes' },
        { id: 37, name: 'FFF', circle: 'yes' },
        { id: 59, name: 'GGG', circle: 'yes' },
        { id: 43, name: 'HHH', circle: 'yes' },
        { id: 35, name: 'JJJ', circle: 'yes' },
        { id: 100, name: 'JJJ', circle: 'yes' }
    ],
    arrayList = [], obj_c_processed = [];

for (var i in g) {
    var obj = {id: g[i].id, name: g[i].name, goal: g[i].goal};

    for (var j in c) {
        if (g[i].id == c[j].id) {
            obj.circle = c[j].circle;
            obj_c_processed[c[j].id] = true;
        }
    }

    obj.circle = obj.circle || 'no';
    arrayList.push(obj);
}

for (var j in c){
    if (typeof obj_c_processed[c[j].id] == 'undefined') {
        arrayList.push({id: c[j].id, name: c[j].name, goal: 'no', circle: c[j].circle});
    }
}

console.log(arrayList);
Sign up to request clarification or add additional context in comments.

5 Comments

The code is working thanks. Its possible to simplify this code ?
I have edited my answer. You can assign multiple variables with only one var keyword, seperated by a comma. I simplified that, I removed the get* variables and I removed the use of in_obj_c using the || shorthand (in this case: assign "no" to obj.circle if it's empty)
Hi, I need one more help. The same question but i have 3 variable. (g,c,and u). g and c are having same values. var u = [ { 'id': 101, 'name': 'TTT',"other":"yes" }, { 'id': 40, 'name': 'BBB' ,"other":"yes"}, { 'id': 50, 'name': 'III' ,"other":"yes"}, { 'id': 100, 'name': 'JJJ' ,"other":"yes"} ]
Expected : [ { 'id': 36, 'name': 'AAA', 'goal': 'yes','circle': 'yes','other':'no' }, { 'id': 40, 'name': 'BBB', 'goal': 'yes','circle': 'yes','other':'yes'"}, { 'id': 57, 'name': 'CCC', 'goal': 'yes','circle': 'yes','other':'no' }, { 'id': 4, 'name': 'DDD', 'goal': 'yes' ,'circle': 'yes','other':'no' }, { 'id': 39, 'name': 'EEE', 'goal': 'yes' ,'circle': 'yes','other':'no' }, { 'id': 37, 'name': 'FFF', 'goal': 'yes' ,'circle': 'yes','other':'no'}, { 'id': 59, 'name': 'GGG', 'goal': 'yes' ,'circle': 'yes','other':'no'}, { 'id': 50, 'name': III, 'goal': 'yes' ,'circle': 'no','other':'yes'},
{ 'id': 43, 'name': 'HHH', 'goal': 'yes' ,'circle': 'yes','other':'no'}, { 'id': 35, 'name': JJJ, 'goal': 'yes' ,'circle': 'yes','other':'no'} , { 'id': 42, 'name': 'ZZZ', 'goal': 'no' , 'circle': 'yes','other':'no'}, { 'id': 100, 'name': JJJ,'goal': 'no' , 'circle': 'yes' ,'other':'yes'}, { 'id': 101, 'name': TTT,'goal': 'no' , 'circle': 'no' ,'other':'yes'}]
4

Using undescore.js, you can write some function like this:

var a = [ { id: 36, name: 'AAA', goal: 'yes' },
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 57, name: 'CCC', goal: 'yes' },
    { id: 4, name: 'DDD', goal: 'yes' },
    { id: 39, name: 'EEE', goal: 'yes' },
    { id: 37, name: 'FFF', goal: 'yes' },
    { id: 59, name: 'GGG', goal: 'yes' },
    { id: 50, name: 'III', goal: 'yes' },
    { id: 43, name: 'HHH', goal: 'yes' },
    { id: 35, name: 'JJJ', goal: 'yes' } ];

var b = [ { id: 36, name: 'AAA', circle: 'yes' },
    { id: 40, name: 'BBB', circle: 'yes' },
    { id: 57, name: 'CCC', circle: 'yes' },
    { id: 42, name: 'ZZZ', circle: 'yes' },
    { id: 4, name: 'DDD', circle: 'yes' },
    { id: 39, name: 'EEE', circle: 'yes' },
    { id: 37, name: 'FFF', circle: 'yes' },
    { id: 59, name: 'GGG', circle: 'yes' },
    { id: 43, name: 'HHH', circle: 'yes' },
    { id: 35, name: 'JJJ', circle: 'yes' },
    { id: 100, name: 'JJJ', circle: 'yes' } ];


function merge_object_arrays (arr1, arr2, match) {
  return _.union(
    _.map(arr1, function (obj1) {
      var same = _.find(arr2, function (obj2) {
        return obj1[match] === obj2[match];
      });
      return same ? _.extend(obj1, same) : obj1;
    }),
    _.reject(arr2, function (obj2) {
      return _.find(arr1, function(obj1) {
        return obj2[match] === obj1[match];
      });
    })
  );
}

document.getElementsByTagName('pre')[0].innerHTML = JSON.stringify(
  merge_object_arrays(a, b, 'id'), null, 2
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<pre>
</pre>

Try running it here.

1 Comment

How would you chance this to make items from arr2 override arr1 on id = id and name !=name
0

Try using jquery. Try this :

var g= [ 
    { id: 36, name: 'AAA', goal: 'yes' },
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 57, name: 'CCC', goal: 'yes' },
    { id: 4, name: 'DDD', goal: 'yes' },
    { id: 39, name: 'EEE', goal: 'yes' },
    { id: 37, name: 'FFF', goal: 'yes' },
    { id: 59, name: 'GGG', goal: 'yes' },
    { id: 50, name: 'III', goal: 'yes' },
    { id: 43, name: 'HHH', goal: 'yes' },
    { id: 35, name: 'JJJ', goal: 'yes' } ];


 var c= [ 
    { id: 36, name: 'AAA', circle: 'yes' },
    { id: 40, name: 'BBB', circle: 'yes' },
    { id: 57, name: 'CCC', circle: 'yes' },
    { id: 42, name: 'ZZZ', circle: 'yes' },
    { id: 4, name: 'DDD', circle: 'yes' },
    { id: 39, name: 'EEE', circle: 'yes' },
    { id: 37, name: 'FFF', circle: 'yes' },
    { id: 59, name: 'GGG', circle: 'yes' },
    { id: 43, name: 'HHH', circle: 'yes' },
    { id: 35, name: 'JJJ', circle: 'yes' },
    { id: 100, name: 'JJJ', circle: 'yes' } ];

var combine_obj={};
$.extend(combine_obj, g, c);

OR using simple javascript

var combine_obj={};
for(var key in g)  combine_obj[key]=g[key];
for(var key in c)  combine_obj[key]=c[key];

2 Comments

What are g and c?
The objects in their example
0

You could do it like this,

var g = [ { id: 36, name: 'AAA', goal: 'yes' },
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 57, name: 'CCC', goal: 'yes' },
    { id: 4, name: 'DDD', goal: 'yes' },
    { id: 39, name: 'EEE', goal: 'yes' },
    { id: 37, name: 'FFF', goal: 'yes' },
    { id: 59, name: 'GGG', goal: 'yes' },
    { id: 50, name: 'III', goal: 'yes' },
    { id: 43, name: 'HHH', goal: 'yes' },
    { id: 35, name: 'JJJ', goal: 'yes' } ]


 var c = [ { id: 36, name: 'AAA', circle: 'yes' },
    { id: 40, name: 'BBB', circle: 'yes' },
    { id: 57, name: 'CCC', circle: 'yes' },
    { id: 42, name: 'ZZZ', circle: 'yes' },
    { id: 4, name: 'DDD', circle: 'yes' },
    { id: 39, name: 'EEE', circle: 'yes' },
    { id: 37, name: 'FFF', circle: 'yes' },
    { id: 59, name: 'GGG', circle: 'yes' },
    { id: 43, name: 'HHH', circle: 'yes' },
    { id: 35, name: 'JJJ', circle: 'yes' },
    { id: 100, name: 'JJJ', circle: 'yes' } ]

for (i = 0; i < g.length; i++) {        //Loop trough first array
    var curID = g[i].id;                //Get ID of current object
    var exists = false;                 
    for (j = 0; j < c.length; j++) {    //Loop trough second array
        exixts = false;
        if (curID == c[j].id){          //If id from array1 exists in array2
            exixts = true;
            tempObj = c[j];             //Get id,object from array 2
            break;
        }
    }
    if(exixts) {
        g[i]["circle"] = tempObj.circle;//If exists add circle from array2 to the record in array1
    }else{
        g[i]["circle"] = "no";          //If it doesn't add circle with value "no"
    }
}

for (i = 0; i < c.length; i++) {        //Loop trough array 2
    var curObj = c[i];
    var ex = true;
    g.forEach(function(row) {           //Loop to check if id form array2 exists in array1
        if (curObj.id == row.id){
            ex = false;
        }
    });
    if(ex){                             //If it doesn't exist add goal to object with value "no" and push it into array1
        curObj["goal"] = "no";
        g.push(curObj);
    }
}

console.debug(g);

I've added some comments to explain what is going on in the code.

Psuedo code,

//Loop trough g
//get id from g[i] and check if it exists in c
//if so
    //add circle from a2 to a1[i]
    //Add value of circle from c onto g[i]["circle"]
//otherwise
    //Add value of "no" onto g[i]["circle"]

//Loop trough c
    //If id isn't in g, add row with value c[i]["goal"] = "no" to g

Comments

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.