0

So I know I can retrieve properties from an object by string with bracket notation:

const obj = {a:[
  {b: 'hi'},
]};

console.log(obj['a']); // Array [Object { b: "hi" }]

But if I try to access the item in the array with that notation, it doesn't allow it:

console.log(obj['a[0].b']);  // undefined
console.log(obj['a[0]']);    // undefined

Is there a way to do this in javascript?

Why am I doing this?

So my function is getting strings with array and object information like this:

  • "folder[2].people[1].name.firstName"
  • "folder[2].people[1].name.lastName"
  • "folder[2].name"

and I need to get that information from the object itself. I'd prefer to not have to parse the string.

3
  • How are you constructing the string? Commented May 13, 2021 at 20:52
  • There is no a[0] as a property/key, that's why you get the error. Your object prop a is an array of objects. Commented May 13, 2021 at 20:56
  • What function is this that is returning these strings? Commented May 13, 2021 at 23:58

4 Answers 4

1

Have you tried using... eval()? (more info here)

WARNING: Never use eval()! (read this)

const obj = {
  a: [
    { b: 'hi' },
  ]
};
console.log(eval('obj.a[0].b'));
// prints "hi"
Sign up to request clarification or add additional context in comments.

Comments

1

Use this: console.log(obj['a'][0].b);

 const obj = {a:[
  {b: 'hi'},
]};
console.log(obj['a'][0].b);

Comments

1

You're combining all your keys into a single string so it's looking for a key that matches that string.

Try

console.log(obj['a'][0])
console.log(obj['a'][0]['b'])

Comments

0

if you run it on the browser console(F12) it will be very clear

when you do obj['a'] it already return the array [{ b: 'hi' },]
then you get b by [{ b: 'hi' },][0].b
so the correct way is obj['a'][0].b

obj['a[0]'] means you trying to get

obj = { 
  'a[0]':??? // <= this
};

which doesn't exist

const obj = {a:[
    {b: 'hi'},
  ]};
console.log("obj['a'] = ", obj['a']);
console.log("obj['a'][0] = ", obj['a'][0]);
console.log("obj['a'][0].b = ", obj['a'][0].b);

obj = {'a[0]':"test"};
console.log(obj['a[0]']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.