简体   繁体   中英

Better / Faster way to extract value with a matched property on different depth on a nested object with condition

I have an object with inconsistent nesting structure that I have no control over. I need to extract certain value if it met a certain condition.

currently doing it by iterating over the properties recursively and matching the properties with the condition and pushing the matched values to an empty array like this:

var obj = {"a":0,"b":{"x":1,"y":100},"c":[{"x":1,"y":120},{"x":2,"y":140}]};
var extracts = [];
extractProp(obj);

function extractProp(obj){
    for (var key in obj){
        if (key == "x" && obj[key]=="1"){
            extracts.push(obj["y"]);
        } else {
            extractProp(obj[key]);
        }
    }
}
console.log(extracts); //(2) [100, 120]

which allows me to get the expected result. In my previous question , someone pointed out a better way in modifying parts of json by passing reviver parameter on JSON.parse. It got me thinking that there must be a better way to do this too. Are there any native / built-in function in javascript for this?

Not quite much better but faster

Check comparision here http://jsben.ch/7OZfP

 let obj = { "a": 0, "b": { "x": 1, "y": 100 }, "c": [{ "x": 1, "y": 120 }, { "x": 2, "y": 140 }] }; var extracts = []; extractProp(obj); function extractProp() { Object.entries(obj).forEach(([key, val]) => { if (typeof val === 'object') { if (Array.isArray(val)) { val.forEach(gety) } else { gety(val) } } }); } function gety({ x, y }) { if (x == 1 && y) extracts.push(y); } console.log(extracts); //(2) [100, 120] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM