Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

javascript - Remove object from array of objects

I have an array of objects:

[{"value":"14","label":"7"},{"value":"14","label":"7"},{"value":"18","label":"7"}]

How I can delete this item {"value":"14","label":"7"} resulting in the new array:

 [{"value":"14","label":"7"},{"value":"18","label":"7"}]

?

question from:https://stackoverflow.com/questions/29997710/remove-object-from-array-of-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In ES6 (or using es6-shim) you can use Array.prototype.findIndex along with Array.prototype.splice:

arr.splice(arr.findIndex(matchesEl), 1);

function matchesEl(el) {
    return el.value === '14' && el.label === '7';
}

Or if a copy of the array is ok (and available since ES5), Array.prototype.filter's the way to go:

var withoutEl = arr.filter(function (el) { return !matchesEl(el); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...