How can I access different JSON objects in JavaScript by a variable containing the attribute's path?
var item = {
"car": {
"manufacturer": "Ford",
"model": "Taunus"
"surface": {
"color": "silver",
"type": "metallic"
}
"built (year)": "1975"
};
let foo = "model";
let bar = "surface.color";
consloe.log("Model: " item[foo]); // Output: "Taunus"
console.log("Surface color:" item[bar]); // Output: "undefined", Desired output "silver"
This notation represents only one hierarchic level per set of brackets, of course. Is there an easy elegant way to access several levels with only one labeling variable like "one.two" and "one.two.three"?
CodePudding user response:
You can create a function that will split the string with .
(dot) as the delimiter into an array of strings, and use them to traverse the object in a reducer function.
const item = {
"car": {
"manufacturer": "Ford",
"model": "Taunus",
"surface": {
"color": "silver",
"type": "metallic"
},
"built (year)": "1975"
}
}
const foo = "car.model";
const bar = "car.surface.color";
function get(path) {
const parts = path.split(".");
return parts.reduce((obj, part) => obj[part], item);
}
get(foo); // should return "Taunus"
get(bar); // should return "silver"