0

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"?

Robbit
  • 59
  • 7
  • it looks for a key having name `surface.color` which doesnt exist – cmgchess Feb 13 '22 at 03:55
  • Exactly. I do know, why this doesn't work. :-) But I wonder if there's a way to access the attribute like this without exploding the variable bar and run through its parts by a for loop. – Robbit Feb 13 '22 at 03:58
  • guess youll have to go with this https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path – cmgchess Feb 13 '22 at 04:03

1 Answers1

1

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"
  • This works for me. Thank You very much. I've adapted it for more universal usage: `function getJSON(object, path) { const parts = path.split("."); return parts.reduce((obj, part) => obj[part], object); };` – Robbit Feb 13 '22 at 18:34