I searched a while but couldn't find the answer that I want. I am have a very simple question, how to get rid of the empty objects from Map.
const friuts = [{
apple: 'red',
banana: 1
},
{
apple: 'green',
banana: 1
},
{
apple: 'yellow',
banana: 3
}
]
const newObject = friuts.map(e =>
({ ...e.banana === 1 ? {
apple: e.apple
} :
[]
})
)
console.log(newObject)
If you check the console.log it contains an empty object at the end
[
{
"apple": "red"
},
{
"apple": "green"
},
{} <--- empty
]
Also I tried undefined
or below code, but just can't get rid of the empty objects.
...e.banana === 1 &&
{
apple: e.apple
}
I understand this can be easily done by using other methods like filter
. However, I am learning Map
, so I'd like to learn how to get rid of the empty objects from map.
Sorry for if the question has been asked before. I will remove the question if it is duplicated.
CodePudding user response:
To remove empty objects from the resulting array, you can use the filter method to exclude them from the final array. You can use the Object.keys method to check if the object is empty or not. Here is an example:
const fruits = [{
apple: 'red',
banana: 1
},
{
apple: 'green',
banana: 1
},
{
apple: 'yellow',
banana: 3
}
];
const newObject = fruits
.map(e => ({ ...e.banana === 1 ? { apple: e.apple } : {} }))
.filter(e => Object.keys(e).length > 0);
console.log(newObject);
In the code above, the map method is used to create a new array with only the apple property for objects that have a banana property with a value of 1. The resulting array may contain empty objects, so the filter method is used to exclude them from the final array.
Note that I also removed the square brackets from the object spread syntax in the map method to avoid creating an array of objects. Instead, a new object is created using the spread operator, which will be included in the resulting array.