Skip to content
Advertisement

How can I convert an indexed JavaScript object to an array of objects?

I have an object that looks like this:

JavaScript

I’m trying to convert it into an array of objects so I can do obj.map((obj, idx)=>{//display obj.price and obj.serialNumber//}), so I want to convert obj into an array like this:

JavaScript

I initially used array = Object.values(obj['serialNumber']) to just get serialNumber, but due to the way Object.values works, I can’t just do array = Object.values(obj['serialNumber','price']) to get both. The values() function will ignore the serialNumber field and just make an array of prices. Any help would be appreciated!

Advertisement

Answer

You can use array#reduce with Object.entries() to convert your object to array.

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