Skip to content
Advertisement

Using .map() to iterate over an array of Object values and reassign to new keys

I am trying to transform the data below from:

JavaScript

To:

JavaScript

I have been puzzling away at this for quite a while and can only get it looking like this, which is just seperate objects rather than a single object as part of an array of objects (there are other book objects in the returned JSON from my db the function needs to churn through)

JavaScript

Here is the code I have been working on:

JavaScript

Advertisement

Answer

When mapping the values, instead of constructing an object containing a single property, return an entry pair (an array where the first value is the property, and the second value is the associated value) so that you can turn the array of entries into an object with Object.fromEntries.

JavaScript

This depends on the properties in your input objects being ordered. While this is usually dependable, it’s not a good thing to rely on, and won’t work if any of the properties become numeric (eg 1 or 5). Consider if the input object properties could be formatted as an (ordered) array instead.

Advertisement