Skip to content
Advertisement

How to convert an array with one object and multiple keys into an array of multiple objects using those keys and their values?

I have an array like so with a single object inside:

JavaScript

I want to convert it so that every key-value pair (where the value is a number) in the object is in its own object like the following:

JavaScript

Here, each key was assigned a new key called name, and the value for the original key was assigned a new key called value. Those pairs are then put into their own object inside the array.

Note that “category”: “None” is not its own object in the array since “None” is non-numerical.

It’s also important to note that there could be many key-value pairs, so it’s not just limited to the items above (e.g., “ARFE”: 553.5, etc.)

What I have so far:

I know you can separate a single object into multiple objects:

JavaScript

I also know how that you can create a new object with new keys like so:

JavaScript

However, I’m having trouble putting everything together. How would I be able to achieve NewArray from FirstArray?

Advertisement

Answer

You were pretty close. All you needed to do is specify the name:

JavaScript

Also, if you don’t want { "name": "category", "value": "None" } to be included in the result, you can just filter it:

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