简体   繁体   中英

How can I completely remove an object from an array in Javascript?

I have been using the following code:

formData.objectiveDetails.push(emptyObjectiveDetail);

This pushes a new emptyObjectiveDetail object onto the end of an array called objectiveDetails.

If for example the array of objectiveDetails contains 13 objects then how could I remove the one at position 5? I assume I could make this null but what I want to do is to completely remove it so the length of the array becomes 12.

This might be off topic but I have been considering adding underscore.js. Is this something that could be done with underscore?

formData.objectiveDetails.splice(5, 1)

第一个参数是数组索引,第二个参数是从该索引开始删除的项目数。

You can use Splice to remove the object from the array. Something like this:-

formData.objectiveDetails.splice(5, 1)

使用underscore.js

objectiveDetails = _.without(objectiveDetails, _.findWhere(arr, {id: 5}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM