My objective here is to convert the input
array into the structure of the output
array.
The input array and output array are shown below. If you observe carefully we can see that id is common in both the arrays and only title changes.
var output = [{
id: "1",
title: 'title',
children: [],
},
{
id: "2",
title: 'title2',
children: [],
},
{
id: "3",
title: 'title3',
children: [{
id: "4",
title: 'title4',
children: [],
}, {
id: "5",
title: 'title5',
children: [{
id: "6",
title: 'title6',
children: [],
}, {
id: "7",
title: 'title7',
children: [],
}, {
id: "9",
title: 'title9',
children: [],
}]
}],
}
]
var input = [{
id: "1",
title: 'title_chnaged',
children: [],
},
{
id: "2",
title: 'title_changed',
children: []
},
{
id: "3",
title: 'title_changed',
children: [{
id: "4",
title: 'title_changed',
children: [],
}, {
id: "5",
title: 'title_changed',
children: [],
children: [{
id: "6",
title: 'title_changed',
children: [],
},
{
id: "7",
title: 'title_changed',
children: [],
}
]
}],
},
{
id: "9",
title: 'title_chnaged',
children: [],
}
]
This function will look into the input array of corresponding element of output array on the . basis of id
let found;
function findTheKey(id, widget) {
let newObj = [...widget];
for (var key in newObj) {
if (newObj[key]["id"] == id) {
found = newObj[key];
break;
}
if (newObj[key].hasOwnProperty("children")) {
findTheKey(id, newObj[key].children);
}
}
return found;
}
This function will iterate over the output array and look for corresponding element in input array
function findAllObjectOnArray(output) {
let newObj = [...output];
for (let key in newObj) {
newObj[key] = {
...findTheKey(newObj[key]['id'], input),
children: newObj[key].children
};
if (newObj[key].hasOwnProperty("children")) {
findAllObjectOnArray(newObj[key].children, input);
}
}
return newObj;
}
var result = findAllObjectOnArray(output)
console.log(result)
The result is as expected on label 1 but as we move into nested object, it didn't changed.
Please suggest me something which will let it work. Any hint or solution is highly welcome ?