I'm trying to implement a generic method to access a nested object property dynamically.
The path to the property have to be in an array of string.
So to get the label the array of string would be ['type', 'label']
I'm kinda stuck on this problem, any help ?
**Edit snipet : **
Demo
var parent = {
type: {
id: "2",
label: "3",
}
};
function getNestedLabel(ids){
if (ids.length === 1) {
return parent[ids[0]];
}
var result = parent;
for (let i = 0; i < ids.length; i++) {
result = result[ids[i]];
}
return result;
}
console.log(getNestedLabel(["type", "label"]));
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…