[英]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. 在我之前的问题中 ,有人通过在JSON.parse上传递reviver参数来指出修改json部分的更好方法。 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? javascript中是否有本机/内置函数?
Not quite much better but faster 不是更好但更快
Check comparision here http://jsben.ch/7OZfP 在这里检查比较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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.