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.
Asked
Active
Viewed 7,514 times
0

w3debugger
- 2,097
- 19
- 23
-
3As you already know `$products` is an array, so iterate and use `delete` operator. You should search "How to iterate an array?" – Satpal Jun 14 '17 at 06:01
-
luckily this isn't JSON, but a palin ol' javascript Object - doing this with JSON would be painful – Jaromanda X Jun 14 '17 at 06:07
5 Answers
5
Loop through the elements of the array and delete position
from each.
for (var i = 0; i < $products.length; i++) {
delete $products[i].position;
}

Thomas James Tiam-Lee
- 691
- 3
- 9
1
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.

Diego
- 816
- 7
- 17
0
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.

Radhesh Vayeda
- 881
- 7
- 20
-
A Javascript Error occured Uncaught ReferenceError: position is not defined http://local:8181/js/actions.js 430 22 ReferenceError: position is not defined. – w3debugger Jun 14 '17 at 06:24
-
var position = 1; // Example to remove object at second position then use the above code. I thing you might not have defined the position variable – Radhesh Vayeda Jun 14 '17 at 06:25