Merge An Array Of Javascript Objects Based On A Key Property (multilevel)
I have an array of Javascript objects that look like these: data = [{PK: 'Country1', Prop1: 'true', children:[ {PK: 'State1', Prop1: 'true', children:[
Solution 1:
Here is a simple script using a custom merge functionality I've written sometime ago for json-easy-filter Hope it does the right stuff for you. See it in this plunk
var input = ... your data here ...
var groupByPk = function (arr) {
var res = {};
arr.forEach(function (node) {
if (!res[node.PK]) {
res[node.PK] = [
node
];
} else {
res[node.PK].push(node);
}
});
return res;
};
var mergeByPk = function (arr) {
var groups = groupByPk(arr);
var groups2 = [];
for ( var pk in groups) {
var group = groups[pk];
var ress = merge.apply(this, group);
groups2.push(ress.value);
}
return groups2;
};
var mergeData = function(data){
var mergedCountries = mergeByPk(data);
mergedCountries.forEach(function (country) {
var mergedStates = mergeByPk(country.children);
country.children = mergedStates;
mergedStates.forEach(function (state) {
var mergedCities = mergeByPk(state.children);
state.children = mergedCities;
});
});
return mergedCountries;
};
console.log(JSON.stringify(mergeData(input), null, 4));
Post a Comment for "Merge An Array Of Javascript Objects Based On A Key Property (multilevel)"