给定一个任意结构和混合值类型的反序列化 JSON 对象...
var data = {
'a':'A1',
'b':'B1',
'c': [
{'a':'A2', 'b':true},
{'a':'A3', 'b': [1, 2, 3]}
]};
我想返回一个与给定键匹配的值数组。
> my_func(data, 'a')
['A1', 'A2', 'A3']
> my_func(data, 'b')
['B1', true, [1, 2, 3]]
我得到的最接近的是这个,它给出了正确的结果,但我认为有更好(更快/更整洁/更有效)的解决方案。
my_func = function(o,s,a){
var a = a || [];
if(o == null){
return a;
}
if(s in o){
a.push(o[s]);
}
for(e in o){
if(typeof(o[e]) == "object"){
a.concat(my_func(o[e], s, a))
}
}
return a;
}
有什么想法吗?
最佳答案
function traverse(obj,func, parent) {
for (i in obj){
func.apply(this,[i,obj[i],parent]);
if (obj[i] instanceof Object && !(obj[i] instanceof Array)) {
traverse(obj[i],func, i);
}
}
}
function getPropertyRecursive(obj, property){
var acc = [];
traverse(obj, function(key, value, parent){
if(key === property){
acc.push({parent: parent, value: value});
}
});
return acc;
}
这样称呼
getPropertyRecursive( myobj, 'test' )
其中 myobj
是嵌套对象,test
是键
关于javascript - 通过 JSON 中的键查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33378341/