3

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"}
];
oded
  • 179
  • 1
  • 2
  • 11
  • You need to use delete: `delete array[i][key]` – Oskar Apr 05 '17 at 10:08
  • You're trying to remove a property from an object and not an array. You can use delete for that – Pineda Apr 05 '17 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?*](http://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – T.J. Crowder Apr 05 '17 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 Apr 05 '17 at 10:11
  • 2
    Possible duplicate of [How do I remove a property from a JavaScript object?](http://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – Jonast92 Apr 05 '17 at 10:12
  • sorry i ddin't saw it. the first comment here by @Oskar solve me the problom – oded Apr 05 '17 at 10:13

2 Answers2

9

Use this:

myArray.forEach(function(item){ delete item.id });
Rahul Arora
  • 4,503
  • 1
  • 16
  • 24
  • If that's what the OP's asking, we don't need *yet another* answer to [this question](http://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object). – T.J. Crowder Apr 05 '17 at 10:10
  • ...and they've now confirmed that yes, that's what they're asking. – T.J. Crowder Apr 05 '17 at 10:11
4

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.

tbarreno
  • 76
  • 1
  • 5