0

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?

Lahari
  • 57
  • 8
  • 1
    Why is `items` an array of objects with a single property, rather than one object with multiple properties? – Ivar Aug 26 '21 at 14:41
  • Does this answer your question? [Remove array element based on object property](https://stackoverflow.com/questions/15287865/remove-array-element-based-on-object-property) Instead of `obj.property == "value"` or `obj.property != "value"`, just use `!obj.property` or `!obj.hasOwnProperty("property")` – Heretic Monkey Aug 26 '21 at 14:47
  • Is that the wrong way of using array of objects? @Ivar – Lahari Aug 26 '21 at 15:01
  • @HereticMonkey That provides one solution but I also wanted to know why it is leaving an empty object? – Lahari Aug 26 '21 at 15:02
  • Because you're removing the `fruits` property from the object, not the object from the array. – Heretic Monkey Aug 26 '21 at 15:04
  • Yeah now I know why. Thank you :) – Lahari Aug 26 '21 at 15:05
  • 1
    @eerily There might be valid use cases for it, but an object _is_ a collection of properties. It doesn't make much sense to split them up into one object per property and then add them all to an array. WIth a single property, the destructuring, or simply `delete items.fruits` would've been enough. Now you need extra, potentially unnecessary steps. – Ivar Aug 26 '21 at 15:06

3 Answers3

3

Please use filter function.

var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}];
const result = items.filter(val => !val.hasOwnProperty("fruits"));
console.log(result);
Kirill Savik
  • 1,228
  • 4
  • 7
3

Try this

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

console.log(items.filter(item => !item.hasOwnProperty('fruits')))
Sanket Shah
  • 2,888
  • 1
  • 11
  • 22
2

.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);
David
  • 208,112
  • 36
  • 198
  • 279