Created
June 19, 2019 01:24
-
-
Save nishanbajracharya/f68525821f0fbb1345586a045f114525 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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