I saw these two questions:
But they do not work for me.
So I have a nested dynamic array like this:
const data = [
{
id: 1,
subData: [
{
id: 2,
subData: []
},
{
id: 3,
subData: [
{
id: 4,
subData: []
}
]
}
]
},
{
id: 5,
subData: []
},
.
.
.
]
I have to move the nested elements with their "id"
. For example, how can I write a function that gives me the following result:
const data = [
{
id: 1,
subData: [
{
id: 2,
subData: []
},
{
id: 3,
subData: [] // object with id 4 was here
}
]
},
{
id: 5,
subData: []
},
{
id: 4, // now its here
subData: []
}
.
.
.
]
What I've tried so far is to write the following function to first find an element with a specific "id"
and then move that object:
const findObjById = (obj, key, value) => {
if (obj[key] === value) {
return obj;
}
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
if (obj[k] && typeof obj[k] === 'object') {
const found = findObjById(obj[k], key, value);
if (found) {
return found;
}
}
}
}
Works to find a specific object. But I could not move the found object