I have following JSON data, If any one of the child name is matching with any of the parent name then i want to create new json set.
var PARENT_CHILD = {
'Newton': ['Plato', 'Aristotle'],
'Aristotle': ['Einstein'],
'Plato': ['Tesla', 'Edison'],
'Einstein': ['Hawking']
};
I want to convert it into like below:
{
"Newton": {
"child": "Plato, Aristotle"
},
"Plato": {
"parent": "Newton",
"child": "Tesla, Edison"
},
"Aristotle": {
"parent": "Newton",
"child": "Einstein"
},
"Einstein": {
"parent": "Aristotle",
"child": "Hawking"
},
"Tesla": {
"parent": "Plato"
},
"Edison": {
"parent": "Plato"
},
"Hawking": {
"parent": "Einstein"
}
}
You can use Array.reduce
on the entries in PARENT_CHILD
, creating a new entry in the output for the parent (if it doesn't already exist) and adding the child
array to it, and then creating a new entry (with parent
property) for each of the children of that parent:
var PARENT_CHILD = { 'Newton': ['Plato', 'Aristotle'], 'Aristotle': ['Einstein'], 'Plato': ['Tesla', 'Edison'], 'Einstein': ['Hawking'] }; var result = Object.entries(PARENT_CHILD).reduce((acc, [parent, child]) => { if (acc[parent]) { acc[parent].child = child.join(', '); } else { acc[parent] = { child: child.join(', ') }; } child.forEach(name => acc[name] = { parent }); return acc; }, {}); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.