Skip to content
Advertisement

(Recursion) How to get all key/value pairs from an Object with nested objects and arrays

I have an object that look like this:

JavaScript

I want an array with pairs of EVERY key in the object with the value.

For example:

JavaScript

Everything Ok until that point. The problem is when a property is an array of objects. The output I want is the following:

JavaScript

So it needs to check if the property is an array and add the position number if so.

I know I need a recursive function but I dont know how to do it. This is what I got until now.

JavaScript

Note: I dont want the empty or null keys.

I would be very grateful if someone can help me. Thanks anyways!

Advertisement

Answer

This does something very similar to what you’re looking for. It’s a technique I use often.

JavaScript
JavaScript

The differences are that there is a separator before the array index and that I use zero-based arrays, not one-based arrays.

I would suggest that it’s a much better output format. If nothing else, it would probably allow you to rehydrate the original format. But if you want to change it, you should probably simply reduce the path to combine the numeric elements with their predecessors, something like:

JavaScript

But this would require changes if the outer object might be an array.

Again, though, absent a very good reason to use your requested format, I would strongly recommend my alternative.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement