0

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?

pokken
  • 327
  • 1
  • 15
  • IMO your current approach is just fine, the intent of the code is quite clear and there isn't really anything more to trim down. I'd prefer an `Object` method over `for..in`, but `for..in` still works fine here – CertainPerformance Mar 25 '19 at 05:56
  • Fast thinking, I think reviver function will not allow back reference, so if for instance you wanted the inverse (`x` based on the value of `y`) then you'd be screwed. Your method doesn't look that bad from here, except that I would add a few if(hasOwnProperty) and if(obj && typeof obj === "object") – Kaiido Mar 25 '19 at 05:56

1 Answers1

0

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]
AZ_
  • 3,094
  • 1
  • 9
  • 19