Skip to content
Advertisement

Alternatives to using multiple reduce() functions inside a map() when handling deeply nested array of objects?

I have an object result which has a property records which is an array of objects with a single sample below:

JavaScript

I am transforming it to the following shape with a function I have:

JavaScript

This is the function computeData which I used to map over the array and then apply reduce() twice in order to get the object in the format I need. filters is an array which contains the keys of the final object. I am aware this is not the most efficient manner to do so, therefore I need help with improving this and not using reduce() twice in function computeData.

JavaScript

Advertisement

Answer

Given the array of responses, you can map them to an array of entries for the new object by using the index parameter in .map and concatenating with 'question'. Then pass the result to Object.fromEntries.

The other properties like "Longitude:5.1193" can be split on : and also be passed to Object.fromEntries.

JavaScript
Advertisement