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
  • 128
  • 1
  • 11
  • 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

2 Answers2

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"
Michael Boñon
  • 164
  • 2
  • 8
  • 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
1

This is probably to late to help you and i see everywhere that you cant use vaiables in dot notation but this is the way i do it. Hope it helps.

I just save the variables as string and then pass them through with square brackets.

Example:

    var item = {
    "car": {
       "manufacturer": "Ford",
       "model": "Taunus",
       "surface": {
           "color": "silver",
           "type": "metallic"
       },
       "built (year)": "1975",
 }};

let foo = "model";
let bar = "surface";
let color = `color`;

console.log("Model: " + item.car[foo]);          // Output: "Taunus"
console.log("Surface color:" + item[bar]);   // Output: "undefined", Desired output "silver"
console.log(`--------------------------------------------`)
console.log(`Model: ${item.car[foo]}`); // Output: `Taunus`
console.log(`Surface Color: ${item.car[bar][color]}`); //Output: `Surface Color: silver`

Hopefully that is of some help for you :)

Gromit
  • 77
  • 8