Skip to content
Advertisement

For IN Loop inside Map Javascript

Given the current example array of objects:

JavaScript

I need to iterate through the objects and do 3 things: Delete empty objects Delete empty keys Modify key names and delete the word “dependence”

The new array should look like:

JavaScript

What I tried so far:

JavaScript

Is there an elegant way to do this? I feel I’m mutating state in ways I shouldn´t.

Advertisement

Answer

The following code uses the side-effect-free style frequently found in React/Redux codebases. You could also implement this in a more performant fashion by making in-place changes.

noFalsyProps takes an array of entries (from an Object.entries call) and eliminates all properties with a falsy (eg. empty string) value.

correctPropNames takes an array of entries and ensures instances of the string 'dependence' are removed.

transform uses Arrray#reduce to remove all objects with no own properties; for the remainder it transforms the objects using noFalsyProps and correctPropNames.

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