Yusnee Yusnee - 1 month ago 5
Javascript Question

Merge new array objects to existing object js

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'],
}];

Answer

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"]);
Comments