[英]How do I remove an object inside a JSON object in Angular?
我的問題是這樣的。 我在下面有一個 JSON 對象。 我想刪除分配為 1 的對象。我已經遍歷了它,我最好的人似乎無法刪除該特定對象。
0: Object
teller_id: 1
details: CASH
assignments: Array [2]
0: Object <---- Remove this Object and all the elements indside it
service_id: 1
status: 1
assignment: 1
1: Object
service_id: 1
status: 1
assignment: 2
1: Object
teller_id: 2
details: EMP
assignments: Array [2]
0: Object
service_id: 2
status: 3
assignment: 4
1: Object
service_id: 2
status: 4
assignment: 6
刪除賦值為 1 的對象
0: Object
teller_id: 1
details: CASH
assignments: Array [2]
1: Object
service_id: 1
status: 1
assignment: 2
1: Object
teller_id: 2
details: EMP
assignments: Array [2]
0: Object
service_id: 2
status: 3
assignment: 4
1: Object
service_id: 2
status: 4
assignment: 6
它刪除了在 assignments 數組中找到的 Object[0]。 謝謝
這些都不需要 Angular,因為它涉及純 JavaScript。
在每個對象中, assignments
都是一個數組。 雖然數組是對象的一種形式,但它有自己的屬性。 有幾種方法可以解決這個問題。
首先,如果您希望將其視為數組,則:
myObject[0].assignments.splice(0,1); // remove first element from array
或者:
myObject[0].assignments.shift(); // get first element from array
然而,這將在數組中向下移動分配的索引。 即 assignments[1] 將變成 assignments[0]。
如果你不想改變指數,然后delete
是你在找什么:
delete myObject[0].assignments[0];
然而,這將導致數組的第一個元素具有值undefined
。
讓指向對象的變量名是ar
:
delete ar[0].assignments[0];
我希望您在循環和查找元素時不會遇到問題。
您可以使用 splice 函數從數組中刪除元素
var arr = [{name: 'Ram', assiignment: 1}, {name: 'Raju', assiignment: 2}];
arr.splice(0,1); // Here 0 is the index of element to be delete and 1 is how many elements to delete from that index we provided
之后你的陣列會像這樣:
[{name: 'Raju', assiignment: 2}]
你可以做類似的事情
angular.forEach(items, function (item) {
for(var i = item.assignments.length - 1; i >=0; i--) {
if (item.assignments[i].assignment === 1) {
item.assignments.splice(i, 1);
}
}
});
這對於 angular native 是有問題的。
如果你使用的是像 lodash 或 underscore 這樣的第三方庫,它會更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.