javascript - delete data from JSON object - Stack Overflow

I've following output codeI want to remove position from array. When I try delete $products.positi

I've following output code

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.

I've following output code

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.

Share Improve this question asked Jun 14, 2017 at 6:00 w3debuggerw3debugger 2,10219 silver badges24 bronze badges 2
  • 3 As you already know $products is an array, so iterate and use delete operator. You should search "How to iterate an array?" – Satpal Commented Jun 14, 2017 at 6:01
  • luckily this isn't JSON, but a palin ol' javascript Object - doing this with JSON would be painful – Jaromanda X Commented Jun 14, 2017 at 6:07
Add a ment  | 

5 Answers 5

Reset to default 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;
}

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.

try this

$products.forEach(function(item){ 
    delete item.position; 
});

There are multiple methods to remove an JSON object from particular position from an array, but I will remended to use splice method since its paratively 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.

This one works for me.

for(var i in $products){
    delete $products[i].position;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742276585a4413703.html

相关推荐

  • javascript - delete data from JSON object - Stack Overflow

    I've following output codeI want to remove position from array. When I try delete $products.positi

    21小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信