My question goes like this. I have a JSON object below. I want to remove the object that has an assignment 1. I already looped through it and by the best of me I cannot seem to remove that particular object.
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
Remove object with an assignment of 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
In which it removes the Object[0] found inside the assignments array. Thanks
None of this really needs Angular, because it involves pure JavaScript.
In each object, assignments
is an array. Whilst an array is a form of object, it has its own properties. There are a few ways to approach this.
Firstly if you wish to treat it as an array, then:
myObject[0].assignments.splice(0,1); // remove first element from array
or:
myObject[0].assignments.shift(); // get first element from array
This will however move the indexes of the assignments down in the array. ie assignments[1] will become assignments[0].
If you don't want to change the indices, then delete
is what you're looking for:
delete myObject[0].assignments[0];
This will however cause the first element of the array to have the value undefined
.
Let the variable name that points to the object is ar
:
delete ar[0].assignments[0];
I hope you don't have trouble looping and finding the element.
You can use splice function for delete elements from array
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
After your array will like this:
[{name: 'Raju', assiignment: 2}]
you can do something like
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);
}
}
});
This is problematic with angular native.
If you are using some third party library like lodash or underscore, it will be easier.
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.