Skip to content

Instantly share code, notes, and snippets.

@nishanbajracharya
Created June 19, 2019 01:24
Show Gist options
  • Save nishanbajracharya/f68525821f0fbb1345586a045f114525 to your computer and use it in GitHub Desktop.
Save nishanbajracharya/f68525821f0fbb1345586a045f114525 to your computer and use it in GitHub Desktop.
var input = {
'1': {
id: 1,
name: 'John',
children: [{
id: 2,
name: 'Sally'
},
{
id: 3,
name: 'Mark',
children: [{
id: 4,
name: 'Harry'
}]
}
]
},
'5': {
id: 5,
name: 'Mike',
children: [{
id: 6,
name: 'Peter'
}]
}
};
function normalize(input) {
var keys = Object.keys(input);
return keys.reduce(function(acc, key) {
if (!acc[key]) {
acc[key] = input[key];
}
flattenChild(acc[key], acc);
return acc;
}, {});
}
function flattenChild(obj, parent) {
if (!obj.children) {
return;
}
obj.children.forEach(function(value, index) {
parent[value.id] = value;
obj.children[index] = value.id;
flattenChild(value, parent);
});
}
console.log(normalize(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment