2017-04-24 197 views
0

我有對象的數組,並希望從該數組中刪除一個對象:如何從對象數組中刪除對象在angularjs

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?

+0

_「angularjs or javascript?」_請了解它們之間的區別嗎?請? ---另外,請查看['Array.prototype.filter'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – evolutionxbox

+1

可能的[如何從JavaScript中的數組中刪除特定元素?](http://stackoverflow.com/questions/5767325/how-to-remove-a-particular-element-from-an-array-in-javascript) – evolutionxbox

回答

0

如果每個對象的id都是唯一的,則可以使用數組filter

考慮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)

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

首先,找到該元素的index要刪除:

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

然後用刪除:

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