I have an object that has multiple keys with varying levels of depth. I am looking to create a new object with only the nodes that match the search term:
Desired search term: ‘my search term’.
Original object:
{
grandParent1: {
parent1: {
child1: {
grandChild1: {
name: 'my search term'
},
grandChild2: {
name: 'not my search term'
},
grandChild3: {
name: 'not my search term either'
},
},
child2: {
grandChild1: {
name: 'my search term'
},
grandChild2: {
name: 'not my search term'
}
}
},
parent2: {
child1: {
name: 'my search term'
}
},
parent3: {
name: 'my search term'
}
}
}
What I’m looking for:
{
grandParent1: {
parent1: {
child1: {
grandChild1: {
name: 'my search term'
}
},
child2: {
grandChild1: {
name: 'my search term'
}
}
},
parent2: {
child1: {
name: 'my search term'
}
},
parent3: {
name: 'my search term'
}
}
}
>Solution :
To create a new object with only the nodes that match the search term ‘my search term’ from the original object, you can use a recursive function to traverse the object and filter out the desired nodes. Here’s an example implementation in JavaScript:
function filterObject(obj, searchTerm) {
const filteredObj = {};
for (const key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
const nestedObj = filterObject(obj[key], searchTerm);
if (Object.keys(nestedObj).length > 0) {
filteredObj[key] = nestedObj;
}
} else if (obj[key] === searchTerm) {
filteredObj[key] = obj[key];
}
}
return filteredObj;
}
const originalObject = {
grandParent1: {
parent1: {
child1: {
grandChild1: {
name: 'my search term',
},
grandChild2: {
name: 'not my search term',
},
grandChild3: {
name: 'not my search term either',
},
},
child2: {
grandChild1: {
name: 'my search term',
},
grandChild2: {
name: 'not my search term',
},
},
},
parent2: {
child1: {
name: 'my search term',
},
},
parent3: {
name: 'my search term',
},
},
};
const filteredObject = filterObject(originalObject, 'my search term');
console.log(filteredObject);
In this example, the filterObject
function takes in the original object and the search term as arguments. It recursively traverses the object and checks each value. If a value is an object, it calls the filterObject
function again to filter the nested object. If a value matches the search term, it adds it to the filteredObj
. The function returns the filtered object.
The resulting filteredObject
will contain only the nodes that match the search term.