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"}
];
6
  • You need to use delete: delete array[i][key] 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 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? 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). Commented Apr 5, 2017 at 10:11
  • 2
    Possible duplicate of How do I remove a property from a JavaScript object? Commented Apr 5, 2017 at 10:12

2 Answers 2

9

Use this:

myArray.forEach(function(item){ delete item.id });
Sign up to request clarification or add additional context in comments.

2 Comments

If that's what the OP's asking, we don't need yet another answer to this question.
...and they've now confirmed that yes, that's what they're asking.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.