最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to remove element from array by key in javascript? - Stack Overflow

programmeradmin4浏览0评论

I have this array:

var myArray = [
                  {first_name: "Oded", last_name: "Taizi", id: 1},
                  {first_name: "Ploni", last_name: "Almoni", id: 2}
                  ];

An i want to remove the id element? I create function like this but it doesn't work correctly.

function removeKeys(array,keys){
 for(var i=0; i<array.length; i++){
    for(var key in array[i]){
        for(var j=0; j<keys.length; j++){
            if(keys[j] == key){
                array[i].splice(j, 1);
            }
        }
    }
 }
}

removeKeys(myArray ,["id"]);

The result array should look like:

[
    {first_name: "Oded", last_name: "Taizi"},
    {first_name: "Ploni", last_name: "Almoni"}
];

I have this array:

var myArray = [
                  {first_name: "Oded", last_name: "Taizi", id: 1},
                  {first_name: "Ploni", last_name: "Almoni", id: 2}
                  ];

An i want to remove the id element? I create function like this but it doesn't work correctly.

function removeKeys(array,keys){
 for(var i=0; i<array.length; i++){
    for(var key in array[i]){
        for(var j=0; j<keys.length; j++){
            if(keys[j] == key){
                array[i].splice(j, 1);
            }
        }
    }
 }
}

removeKeys(myArray ,["id"]);

The result array should look like:

[
    {first_name: "Oded", last_name: "Taizi"},
    {first_name: "Ploni", last_name: "Almoni"}
];
Share Improve this question edited Apr 5, 2017 at 10:09 oded asked Apr 5, 2017 at 10:06 odedoded 1791 gold badge2 silver badges11 bronze badges 6
  • You need to use delete: delete array[i][key] – Oskar Commented Apr 5, 2017 at 10:08
  • You're trying to remove a property from an object and not an array. You can use delete for that – Pineda Commented Apr 5, 2017 at 10:08
  • 1 If you're asking how to remove the id property from those objects, this is a duplicate of How do I remove a property from a JavaScript object? – T.J. Crowder Commented Apr 5, 2017 at 10:09
  • Based on your edit, yes, this is a duplicate of the question linked above. I can't dupehammer it (I already voted to close as unclear). – T.J. Crowder Commented Apr 5, 2017 at 10:11
  • 2 Possible duplicate of How do I remove a property from a JavaScript object? – Jonast92 Commented Apr 5, 2017 at 10:12
 |  Show 1 more ment

2 Answers 2

Reset to default 9

Use this:

myArray.forEach(function(item){ delete item.id });

Maybe with a filter on the array:

filteredArray = myArray.filter(item => return (item.id !== id));

This will return a new array without the matching element.

发布评论

评论列表(0)

  1. 暂无评论