0

I'm trying to access a key of an object. But that isn't working. Can anyone help me out here?

So I've an object and a string that points to the value I've to access inside the object. And that value is two levels down.

const obj = { name: 'yash', { hobbies: { sports: ['football', 'tennis']} } };
// this is an example object, I have a string
const item = 'hobbies.sports';
// now I want to access the object with this item
obj[item] // but this isn't working.
Yash
  • 198
  • 1
  • 12
  • Does this answer your question? [JavaScript object: access variable property by name as string](https://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string) – Nico Haase Mar 24 '21 at 15:21
  • Or this? https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable – Nico Haase Mar 24 '21 at 15:21
  • @NicoHaase not really. – Yash Mar 24 '21 at 15:32
  • What do you mean by "not really"? Please edit your question to contain more details – Nico Haase Mar 24 '21 at 16:04

2 Answers2

1

A crude solution to your problem:

const obj = {
  name: 'yash',
  hobbies: {
    sports: ['football', 'tennis']
  }
};
// this is an example object, I have a string
const item = 'hobbies.sports';
// now I want to access the object with this item
console.log(eval("obj." + item))

Here's a better one that doesn't use eval:

const obj = {
  name: 'yash',
  hobbies: {
    sports: ['football', 'tennis']
  }
};
// this is an example object, I have a string
const item = 'hobbies.sports';
// now I want to access the object with this item
output = item.split('.').reduce((acc, el) => acc[el], obj)

console.log(output)
Endothermic_Dragon
  • 1,147
  • 3
  • 13
1

Provided the format of the key ref (item as mentioned) is fixed and is delimited with '.', we can split the keys and then use reduce to come up with the result as below -

const obj = { name: 'yash', hobbies: { sports: ['football', 'tennis']} };
const ref = 'hobbies.sports';

const keys = ref.split('.');
const result = keys.reduce((accumulator, x) => accumulator[x], obj);

console.log(result);
Krantisinh
  • 1,579
  • 13
  • 16