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
2 Answers
Reset to default 9Use 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.