This question already has an answer here:
-
How can I access and process nested objects, arrays or JSON?
22 answers
How to get e
's value without knowing which group, which means only use obj
and e
?
And also can use same way to get a
.
Thanks
let obj:Object = {
a: 'value1',
b: 'value2',
group1: {
c: 'value3',
d: 'value4'
},
group2: {
e: 'value5',
f: 'value6'
}
};
I would do it like this:
function findValue(key, obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (i === key) {
return obj[i];
} else if (typeof(obj[i]) == "object") {
var value = findValue(key, obj[i]);
if (typeof(value) !== "undefined") { return value; }
}
}
}
}
findValue('a', obj);
//"value1"
findValue('e', obj);
//"value5"
You can use Object.keys() to iterate through properties and Object.hasOwnProperty() to test if object contains property:
let key = Object.keys(obj)
.find(k => obj[k].hasOwnProperty('e'));
console.log(obj[key].e);
Version which returns falsy values, too.
function find(key, object) {
var value;
Object.keys(object).some(function (k) {
if (key === k) {
value = object[k];
return true;
}
if (typeof object[k] === 'object') {
value = find(key, object[k]);
return value !== undefined;
}
});
return value;
}
var obj = { a: 'value1', b: 'value2', group1: { c: 'value3', d: 'value4' }, group2: { e: 'value5', f: 'value6' }, group3: { g: '', h: 0 } };
document.write(find('e', obj) + '<br>');
document.write(find('g', obj) + '<br>');
document.write(find('h', obj) + '<br>');