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'],
}];
2
  • 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? Commented Oct 9, 2016 at 1: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. Commented Oct 9, 2016 at 1:22

3 Answers 3

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"]);
Sign up to request clarification or add additional context in comments.

5 Comments

concat as your suggestion not merge it but make new array :(
Ok @Yusnee, see my Edit :)
@ London Smith. Thanks for your effort to help me. But with console.table(countryArray), I lost Penang and Johor. Meaning it only replace, not merge them.
I thought it was the purpose. So concat in the wile...See my update EDIT2 countryArray[i]["state"] = countryArray[i]["state"].concat(newArr[j]["state"]);
@Yusnee Haha :) I'm glad to help
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"));

1 Comment

@ 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.
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

1 Comment

great appreciation for your effort. But I already have my solution for that. Basically is same.

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.