5

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'],
}];
Yusnee
  • 177
  • 11
  • 2
    That seems unnecessarily harsh and not constructive. This isn't exactly a simple question - I couldn't find a simple answer after searching around for a bit - and it's not fair to assume no attempt was made. Clearly she's new to the site and is a beginner - instead of potentially alienating her, maybe you could explain what she could do differently in the future, such as sharing what she's tried already? – A. Damond Oct 09 '16 at 01:02
  • Thank for comments, but don't ever think that I haven't tried anything. I have tried a lot including concat, push and more. Search for any post that will help, but I couldn't solve the problem. That's why I am asking in this forum. And by having that script as in my question, it doesn't mean I have to do a lot? BTW, you are all nice. – Yusnee Oct 09 '16 at 01:22

3 Answers3

5

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"]);
London Smith
  • 1,622
  • 2
  • 18
  • 39
4

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"));
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • @ Oriol God blesh you. Thanks for all of you that have wasted time for me. I't 8:25 AM in my country. I haven't sleep all night looking for help. – Yusnee Oct 09 '16 at 01:27
1

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

Sulung Nugroho
  • 1,605
  • 19
  • 14
  • great appreciation for your effort. But I already have my solution for that. Basically is same. – Yusnee Oct 15 '16 at 11:35