smus Posted March 20, 2019 Share Posted March 20, 2019 const data = { level1: { level2: { level3: 'some data' } } }; Is there a way to get the names of all the keys (at any level) in that object without using a recursion? (level1, level2, level3) Link to comment Share on other sites More sharing options...
Ingolme Posted March 20, 2019 Share Posted March 20, 2019 A recursive function is the easiest way to do it, but it's possible to replace any recursive function with an iterative process and stack memory, though I would advise against it since it's messy. Link to comment Share on other sites More sharing options...
smus Posted March 21, 2019 Author Share Posted March 21, 2019 Yeah, true, same info is on StackOverflow: different implementatoins of recursive approach. Strange that ES6 doesn't have a built-in function or method for it. Object.hasOwnProperty is only for the upper-level keys which makes it useless for structured objects. Link to comment Share on other sites More sharing options...
Ingolme Posted March 21, 2019 Share Posted March 21, 2019 I don't see any practical reason to search for all keys at every level inside an object. If they don't build such a feature into the language it's probably to discourage people from doing it. Link to comment Share on other sites More sharing options...
justsomeguy Posted March 21, 2019 Share Posted March 21, 2019 You would only have a list of keys, you wouldn't know which level they're at. If there are duplicate keys you wouldn't know either. If you want to do that though, why is not using recursion a requirement? Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now