2

NOT duplicate of : Dynamically access object property using variable

How to read the JavaScript Object Array property dynamically.

var person = {
    name: "Ravi",
    age: 25
    friends: [{
            name: "Suresh"
        },
        {
            name: "Nitin"
        },
        {
            name: "Argha"
        }
    ]
}

So, if I want to read any property dynamically, I can use

var dynamicProperty = 'age';
person[dynamicProperty] // Output : 25

But it fails for array.

var dynamicProperty = 'friends[1]';
person[dynamicProperty].name // Output : undefined

What is the best way to pass the name of the array dynamically ?

Community
  • 1
  • 1
Ravi Roshan
  • 1,177
  • 2
  • 11
  • 28
  • 2
    This has nothing to do with "the array". It is about trying to put the accessor for the array **inside the property name of the object** – Quentin Apr 26 '17 at 17:51

1 Answers1

3

You can't access more than a single property at a time using dynamic property access notation. You will need to use an array of keys (often called a "path") in conjunction with Array#reduce:

var person = {
  name: "Ravi",
  age: 25,
  friends: [{
      name: "Suresh"
    },
    {
      name: "Nitin"
    },
    {
      name: "Argha"
    }
  ]
}

function access (o, k) { return o[k] }

var result = ['friends', 1, 'name'].reduce(access, person)

console.log(result)
gyre
  • 16,369
  • 3
  • 37
  • 47