Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search all levels nested Javascript object

I have a Javascript Object that represents a nested JSON string like this:

http://pastebin.com/vwZb1XrA

There are many levels that contain a "name" element. For example "SVI" or "Population" or "Human Development Index".

I am trying to find a way to iterate over every level of the object to find the name "SVI" or "Population" or "Human Development Index". When a match is made I want to then replace the weight value with something like this:

if (data[key].name == name) {
    data[key].weight = 55;
}
like image 507
Bwyss Avatar asked Jan 26 '26 00:01

Bwyss


1 Answers

You can recursively check each and every object, like this

function rec(currentObject, values, replacement) {
    if (values.some(function(currentValue) {
        return currentObject.name === currentValue;
    })) {
        currentObject.weight = replacement;
    }
    (currentObject.children || []).forEach(function(currentItem) {
        rec(currentItem, values, replacement);
    });
}

rec(data, ["SVI", "Population", "Human Development Index"], 55);
console.log(data);

Working demo

like image 167
thefourtheye Avatar answered Jan 27 '26 12:01

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!