Reputation: 2102
I want to remove position from array. When I try delete $products.position;
It is not deleting. But When I try delete $products[0].position;
It is deleting only from first.
Upvotes: 0
Views: 8178
Reputation: 11
This one works for me.
for(var i in $products){
delete $products[i].position;
}
Upvotes: 0
Reputation: 911
There are multiple methods to remove an JSON object from particular position from an array, but I will recommended to use splice method since its comparatively faster then other methods.
products.splice(position, 1);
The first parameter indicates the position to start from and the second indicates the number of objects you want to splice. Since you only want to remove one object, so it should be written 1(one). Position here starts from 0(zero) so insert the position accordingly.
Upvotes: 0
Reputation: 816
I would use map
instead of forEach
.
const products = [{ foo: 'bar', position: 1 }, { foo: 'baz', position: 2}, { doo: 'daz' }];
console.log(products.map(obj => delete obj.position && obj));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Although it is probably less readable it makes more sense to me because you want to generate a new array applying a delete
function to each element.
Upvotes: 1
Reputation: 691
Loop through the elements of the array and delete position
from each.
for (var i = 0; i < $products.length; i++) {
delete $products[i].position;
}
Upvotes: 5