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?

7
  • 1
    Why is items an array of objects with a single property, rather than one object with multiple properties? Commented Aug 26, 2021 at 14:41
  • Does this answer your question? Remove array element based on object property Instead of obj.property == "value" or obj.property != "value", just use !obj.property or !obj.hasOwnProperty("property") Commented Aug 26, 2021 at 14:47
  • Is that the wrong way of using array of objects? @Ivar Commented Aug 26, 2021 at 15:01
  • @HereticMonkey That provides one solution but I also wanted to know why it is leaving an empty object? Commented Aug 26, 2021 at 15:02
  • 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. Commented Aug 26, 2021 at 15:06

3 Answers 3

3

Please use filter function.

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

Sign up to request clarification or add additional context in comments.

Comments

3

Try this

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

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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.