How to call the map method only if the element is an array?
Given an object literal, let us say ‘person’. It has a number of properties of various types. The task here is to map the values of the property only if the property is an Array itself. Instead of an object, we can also perform the same set of operations on an array.
The Array filter() method is used to create a new array from a given array consisting of only those elements which satisfy a condition set by the argument function.
- Convert the object values into an array using Object.values() method. Let it be arr.
- Iterate over the array(arr) using the filter method. The filter returns true if the type of the element is ‘object’.
- Map the resulting array using the map method.
Following are the variations of the given problem:
Example 1:Mapping From an object literal the issue with the above-mentioned approach lies in the fact that neither the filter nor the map method can be used to iterate objects. To work around this problem, Object.Values should be used. Object.Values take an object as a parameter and return an array of all the values in that object. Now we can apply array map() and array filter() methods on this array.
Example 2 : Mapping From an array , we can directly use array map() and array filter() methods here.