Lahari
Lahari

Reputation: 65

Removing object with property in array leaves an empty object

I'm trying to remove an item with a property from array object based on the key but it is leaving an empty object. For example,

var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}]

So I want to remove the item with the fruits property. This is the code I tried...

var filter = items.map(({ fruits, ...rest }) => rest);

This gave me an output of

[{},{"veggies": ["Potato", "Carrot"]}]

Why is it leaving a trace of an empty object? And how to get rid of that empty object?

Upvotes: 0

Views: 333

Answers (3)

David
David

Reputation: 218808

.map will return an array of the same length, mapped to a new array. To remove entries use .filter:

var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}]
var filter = items.filter(i => !i.fruits);
console.log(filter);

Upvotes: 2

Sanket Shah
Sanket Shah

Reputation: 3091

Try this

var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}]

console.log(items.filter(item => !item.hasOwnProperty('fruits')))

Upvotes: 3

Kirill Savik
Kirill Savik

Reputation: 1278

Please use filter function.

var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}];
const result = items.filter(val => !val.hasOwnProperty("fruits"));
console.log(result);

Upvotes: 3

Related Questions