0

I have custom function to get object keys:

function getNested(obj, ...args) {
  return args.reduce((obj, level) => obj && obj[level], obj)
}

This will work with object which contains only object type keys. E.g:

const data = {
    title: "hello",
    user: {
       name:"User name"
    }
}

getNested(data, 'user', 'name') // User name

But what if our object has array type key with objects. E.g:

const data = {
    title: "hello",
    user: {
       name:"User name",
       "posts": [
            {
                "title": "Post title"
            }
       ]
    }
}
 
getNested(data, 'user', 'posts[0]', 'title') // undefined

How to check in nested object keys array keys too in this case?

Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125

1 Answers1

2

With your implementation you can do smth like:

getNested(data, 'user', 'posts', '0', 'title')