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?

1

There are 1 answers

0
AZ_ On

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]