Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge new array objects to existing object js

Tags:

javascript

I have this javascript objects :

var countryArray = [{
 "country" : 'Indonesia',
 "state" : ['DKI','Bali'],
},
 {
 "country" : 'Malaysia',
 "state" : ['Penang','Johor'],
}];

var newArr = [{ "country" : 'Malaysia', "state" : ['Kelantan'] }]

How can I merge or add newArr to the related CountryArray.

Expected result :

var countryArray = [{
 "country" : 'Indonesia',
 "state" : ['DKI','Bali'],
},
 {
 "country" : 'Malaysia',
 "state" : ['Penang','Johor','Kelantan'],
}];
like image 626
Yusnee Avatar asked Oct 09 '16 00:10

Yusnee


3 Answers

concat ?

countryArray = countryArray.concat(newArr);

EDIT Ok, I see, you want to update states of countryArray according to what is in newArr, no more concat:

EDIT2 concat as you want to add states of countryArray according to what is in newArr

   var countryArray = [{
     "country" : "Indonesia",
     "state" : ["DKI","Bali"],
    },
     {
     "country" : "Malaysia",
     "state" : ["Penang","Johor"],
    }];

    var newArr = [{ "country" : "Malaysia", "state" : ["Kelantan"] }];

    alert("Before while: " + countryArray[1]["state"]);
    var i=0;
    while(countryArray[i]) {
      var j=0;
      while(newArr[j]) {
        if(countryArray[i]["country"] == newArr[j]["country"]) {
          countryArray[i]["state"] = countryArray[i]["state"].concat(newArr[j]["state"]);
        }
        j++;
      }
      i++;
    }
    alert("After while: " + countryArray[1]["state"]);
like image 84
London Smith Avatar answered Oct 04 '22 17:10

London Smith


Basically you want a variation of JavaScript merging objects by id which merges the array values.

  1. Create a hash table.
  2. Iterate both arrays and store the data in the hash table, indexed by the ID. If there already is some data with that ID, merge it.
  3. Get an array with the values of the hash map.

var countryArray = [{
  "country" : 'Indonesia',
  "state" : ['DKI','Bali'],
}, {
  "country" : 'Malaysia',
  "state" : ['Penang','Johor'],
}];
var newArr = [{
  "country" : 'Malaysia',
  "state" : ['Kelantan']
}];
function mergeById(objs, id) {
  var hash = new Map();
  objs.forEach(function(obj) {
    var merged = hash.get(obj[id]) || {};
    Object.keys(obj).forEach(function(key) {
      if (key === id) return merged[id] = obj[id];
      if (!merged[key]) merged[key] = [];
      if (Array.isArray(obj[key])) [].push.apply(merged[key], obj[key]);
      else merged[key].push(obj[key]);
    })
    hash.set(obj[id], merged)
  });
  return Array.from(hash.values());
}
console.log(mergeById(countryArray.concat(newArr), "country"));
like image 37
Oriol Avatar answered Oct 04 '22 16:10

Oriol


If you want to merge, sometimes you need to splice as well. Try this :

var countryArray = [{
     "country" : "Indonesia",
     "state" : ["DKI","Bali"],
    },
     {
     "country" : "Malaysia",
     "state" : ["Penang","Johor"],
    }];

To merge with incoming new data ;

 var newArr = [{ "country" : "Malaysia", "state" : ["Kelantan"] }];   

 MergeArray(countryArray,newArr);
 console.table(countryArray);

To Splice form the incoming data ;

var DelArray = [{ "country" : "Malaysia", "state" : ["Penang"] }];

SpliceArray(countryArray,DelArray);
console.table(countryArray);

and the related function ;

function MergeArray(countryArray,newArr) {  
 var a = 0;
  $.each(newArr, function (key, data1) {
     var b = 0;
     $.each(countryArray, function (key, data2) { 

        if(data1.country == data2.country) { // match the same country

    countryArray[b]["state"] =  countryArray[b]["state"].concat(newArr[a]["state"]);

        }

    b++; });
  a++; });  
}

function SpliceArray(countryArray,DelArray) { 
    var a=0;
            $.each(DelArray, function (key, data1) { 
              var b=0;
              $.each(countryArray, function (key, data2) { 

                      if(data1.country == data2.country) {  // get same country    

                         console.log(countryArray[b]["state"]) //   ["Penang", "Johor", "Kelantan"]

                          for(var c=0; c < countryArray[b]["state"].length; c++){   // loop in countryArray state[]

                           console.log(DelArray[a]['state']); // to remove :  ["Penang"]

                              if(countryArray[b]["state"][c] == DelArray[a]['state'] ) {

                                 countryArray[b]["state"].splice(c,1); // remove ["Penang"]

                              }
                          }
                      }
              b++; 
              });
        a++;
        });

  } 

hope will help

like image 45
Sulung Nugroho Avatar answered Oct 04 '22 18:10

Sulung Nugroho