Find duplicate object values in an array and merge them - JAVASCRIPT -



Find duplicate object values in an array and merge them - JAVASCRIPT -

i have array of objects contain duplicate properties: next array sample:

var jsondata = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];

so need merge objects same values of x next array:

var jsondata = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}]

i'm not sure if you're looking pure javascript, if are, here's 1 solution. it's bit heavy on nesting, gets job done.

// loop through objects in array (var = 0; < jsondata.length; i++) { // loop through of objects beyond // don't increment automatically; later (var j = i+1; j < jsondata.length; ) { // check if our x values match if (jsondata[i].x == jsondata[j].x) { // loop through of keys in our matching object (var key in jsondata[j]) { // ensure key belongs object // avoid prototype inheritance problems if (jsondata[j].hasownproperty(key)) { // re-create on values first object // note overwrite values if key exists! jsondata[i][key] = jsondata[j][key]; } } // after copying matching object, delete array // deleting object, "next" object in array moves 1 // hence j prior beingness incremented // why don't automatically increment jsondata.splice(j, 1); } else { // if there's no match, increment next object check j++; } } }

note there no defensive code in sample; want add together few checks create sure info have formatted correctly before passing along.

also maintain in mind might have decide how handle instances 2 keys overlap not match (e.g. 2 objects both having machine1, 1 value of 5 , other value of 9). is, whatever object comes later in array take precedence.

javascript arrays sorting duplicates

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -