When faced with a de-serialized JSON object that has an arbitrary structure and mixed value types...
var data = {
'a':'A1',
'b':'B1',
'c': [
{'a':'A2', 'b':true},
{'a':'A3', 'b': [1, 2, 3]}
]};
The goal is to extract an array of values that correspond to a specific key.
> my_func(data, 'a')
['A1', 'A2', 'A3']
> my_func(data, 'b')
['B1', true, [1, 2, 3]]
The current implementation returns the correct result, but there may be room for improvement in terms of efficiency or readability.
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;
}
Open to suggestions for enhancements.