The code i tried but no change in array
const data = [
{
name: 'Fruit',
children: [{ name: 'Apple' }, { name: 'Banana' }, { name: 'Fruit loops' }],
},
{
name: 'Vegetables',
children: [
{
name: 'Green',
children: [{ name: 'Broccoli' }, { name: 'Brussels sprouts' }],
},
{
name: 'Orange',
children: [{ name: 'Pumpkins' }, { name: 'Carrots' }],
},
],
},
];
output needed
const data = [
{
name: 'Fruit',
children: [{ name: 'Apple' }, { name: 'Banana' }, { name: 'Fruit loops' }],
},
{
name: 'Vegetables',
children: [
{
name: 'Green',
children: [{ name: 'Broccoli' }, { name: 'Brussels sprouts' }],
},
{
name: 'Orange',
children: [{ name: 'Pumpkins' },{name:'newname'} { name: 'Carrots' }],
},
],
},
];
function addObjectBefore(arr, targetName, newObj) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].children) {
addObjectBefore(arr[i].children, targetName, newObj); // Recursive call for nested children array
}
if (arr[i].name === targetName) {
const targetIndex = arr[i]?.children?.findIndex(obj => obj.name === targetName);
arr[i]?.children?.splice(targetIndex, 0, newObj); // Insert new object before the target
break; // Stop the iteration once the target is found and object is inserted
}
}
}
// Given data
const data = [
{
name: 'Fruit',
children: [{ name: 'Apple' }, { name: 'Banana' }, { name: 'Fruit loops' }],
},
{
name: 'Vegetables',
children: [
{
name: 'Green',
children: [{ name: 'Broccoli' }, { name: 'Brussels sprouts' }],
},
{
name: 'Orange',
children: [{ name: 'Pumpkins' }, { name: 'Carrots' }],
},
],
},
];
// Call the function to add the new object
addObjectBefore(data, 'Pumpkins', { name: 'new name' });
// Output the modified data
console.log(data);
2
Answers
After calling
Array::findIndex
you should actually check whether the index is found, it should be>= 0
: