如何从angularjs中的Object数组中删除一个对象

时间:2017-04-24 11:27:33

标签: javascript jquery angularjs json

我有一个对象数组,想要从这个数组中删除一个对象:

var objectArray = [{"id":"John Doe","label":"John Doe","shape":"image","image":"app/data/img/user_icon.png","color":{"background":"#db630d","border":"#7c3400"},"level":0},{"id":"JavaScript","label":"JavaScript","size":30,"shape":"dot","color":{"background":"#00637c"},"level":1},{"id":"C#","label":"C#","size":40,"shape":"dot","color":{"background":"#00637c"},"level":1},{"id":"css","label":"css","size":40,"shape":"dot","color":{"background":"#00637c"},"level":1},{"id":"develop","label":"develop","size":40,"shape":"box","color":{"background":"#65f759","border":"#65f759"},"level":2},{"id":"programming","label":"programming","size":40,"shape":"box","color":{"background":"#65f759","border":"#65f759"},"level":2},{"id":"frontend","label":"frontend","size":40,"shape":"box","color":{"background":"#65f759","border":"#65f759"},"level":2}]

var singleNode = {"id":"frontend","label":"frontend","size":40,"shape":"box","color":{"background":"#65f759","border":"#65f759"},"level":2}

我想从上面提到的对象数组中删除这个对象..我怎么能用angularjs或javascript做到这一点?

3 个答案:

答案 0 :(得分:0)

如果每个对象的filter都是唯一的,则可以使用数组id

id视为唯一



var objectArray = [{"id":"John Doe","label":"John Doe","shape":"image","image":"app/data/img/user_icon.png","color":{"background":"#db630d","border":"#7c3400"},"level":0},{"id":"JavaScript","label":"JavaScript","size":30,"shape":"dot","color":{"background":"#00637c"},"level":1},{"id":"C#","label":"C#","size":40,"shape":"dot","color":{"background":"#00637c"},"level":1},{"id":"css","label":"css","size":40,"shape":"dot","color":{"background":"#00637c"},"level":1},{"id":"develop","label":"develop","size":40,"shape":"box","color":{"background":"#65f759","border":"#65f759"},"level":2},{"id":"programming","label":"programming","size":40,"shape":"box","color":{"background":"#65f759","border":"#65f759"},"level":2},{"id":"frontend","label":"frontend","size":40,"shape":"box","color":{"background":"#65f759","border":"#65f759"},"level":2}]

var singleNode = {"id":"frontend","label":"frontend","size":40,"shape":"box","color":{"background":"#65f759","border":"#65f759"},"level":2}

var filteredArray = objectArray.filter(function(item){
  return item.id !== "frontend";
});

console.log(filteredArray)




答案 1 :(得分:0)

let index = objectArray.findIndex(object => object.id === singleNode.id);
if (index != -1) {
    objectArray.splice(index, 1);
}

答案 2 :(得分:0)

首先,找到要删除的元素的index

var array = [2, 5, 9];
var index = array.indexOf(5);

然后使用splice删除它:

if (index > -1) {
    array.splice(index, 1);
}