0

i need some solutions. Here is my situation; i want to get the value of an array's item within an object using the "KEY". For example, i have this object:

const obj = {
    id: 1,
    fields: [
        {id: 1, name: 'test'},
        {id: 2, name: 'test2'},
    ]
}

and i want to get name's value of the first element in fields. So the solution i know is that we can do: obj['fields'][0]['name'] ... but what i'm looking for is just doing something like obj[KEY].

So the question is: is that possible and what kind of KEY i can use to do it ?

Hsaido
  • 125
  • 12
  • 2
    it is not possible. you need a different approach, like an array with the keys and a fucntion for access. do you have a use case for it? – Nina Scholz Apr 28 '19 at 15:51
  • So it's not possible, yes we can do it using different approachs. I have that case where i want to send a string like that `str = "fields[0].name"` an then according to my string get the value using my string and the entire object. I can do it simply if my object doesn't have arrays, if it has just objects by spliting my string `const keys = str.split('.')` and then using my keys to get the value. – Hsaido Apr 28 '19 at 16:06
  • @NinaScholz can you please explain how this question has already a solution because i checked the link you suggested and i did'nt found any duplication ? – Hsaido Apr 28 '19 at 16:20
  • you have an object/array and a string which should be used as key/s to the value. the access of an array is accessing an object. there is no difference. – Nina Scholz Apr 28 '19 at 16:26
  • No, it's not the same. My question is not about how to access array/object. I already know how to do it and i also know that there are lot of solutions. My question is about if i can use simply stuff like key to access an array's item value without doing that: `obj['fields'][0]['name']`. Anyway tnk you so much, it was amazing to discuss with you about that subject – Hsaido Apr 28 '19 at 16:32
  • 1
    no, it is not possible. please see my first comment. – Nina Scholz Apr 28 '19 at 16:37
  • that was th answer of my question, not duplicate one. Tnk you man – Hsaido Apr 28 '19 at 16:39

1 Answers1

1

This is not possible. You are trying to access a nested value (the property of an array item, inside the property of an object).

Instead, you'll have to be explicit in how you access this field: obj.fields[0].name.

What are you trying to achieve and why do you want to use a single key?

Daniel Apt
  • 2,468
  • 1
  • 21
  • 34
  • I have that case where i want to send a string like that `str = "fields[0].name"` and then according to my string get the value using my string and the entire object. I can do it simply if my object doesn't have arrays, if it has just objects by spliting my string `const keys = str.split('.')` and then using my keys to get the value – Hsaido Apr 28 '19 at 16:07