0

Let's say that I have a uni dimensional dataset like this:

let data = {"adam":19,"james":22,"john":24}

and some HTML like this

  <span id="person" data-path="adam"> 

I can fun a function like this to get the age for the record adam and then inset it into the element with the id of person

let person = document.getElementById('person')
let name = person.dataset.path
let age = data[path]
person.innerHTML = age

I understand that we can use dot (.) within a data-attribute, but I can not use a similar technique as above, where I use a data-attribute as a key to access a multidimensional dataset.

For example, let's say this is my dataset

let multi =    {
        "adam": {
            "age": 19,
            "color": "red"
        }
    }

and my HTML is

  <span id="person" data-path="adam.age"> 

I would expect to be able to access the value of "age" seeing as I can manually access it as multi.adam.age but this does not work.

Does anyone know why using a . from a variable to access multidimensional dataset does not work?

Andy
  • 61,948
  • 13
  • 68
  • 95
Adam Scot
  • 1,371
  • 4
  • 21
  • 41
  • 1
    because it is looking for `let multi = { "adam.age": 19` – epascarello Sep 02 '21 at 00:20
  • 1
    https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path – epascarello Sep 02 '21 at 00:20
  • 1) It's not a "multi-dimensional JSON array", it's an object. 2) _"I would expect"_... why would you expect that result? `data-path="adam.age"` is a _string_. – Andy Sep 02 '21 at 00:25

1 Answers1

1

When you get data-attribute value as adam.age then It will look for "adam.age" property in the multi object which doesn't exist, so it gives undefined

Alternatively, you can achieve this using reduce

let multi = {
  "adam": {
    "age": 19,
    "color": "red"
  }
}

let person = document.getElementById('person')
let name = person.dataset.path
let age = name.split(".").reduce((acc, curr) => acc[curr], multi)
console.log(age);
person.innerHTML = age
<span id="person" data-path="adam.age">
DecPK
  • 24,537
  • 6
  • 26
  • 42