I have a list
let list = [
{
id: "247",
order_number: "21251",
tel: 13911111,
weight: "10kg"
},
{
id: "245",
order_number: "223",
tel: 31,
weight: "10kg"
},
{
id: "123",
order_number: "312312321",
tel: 3213123,
weight: "10kg"
}
];
Now I only wan to remove the specific column, such as 'tel', to get a new list. Is there any elegant way to do it? or I have to loop the whole data to use splice method?
I would argue against using delete keyword because you would be mutating the list instead of making a new one, and also because of its behavior explained in the documentation, Specially those lines about:
Instead you can map()
.
listWithoutTel = list.map(({ tel, ...item }) => item);
Here you'd be using the rest parameters to put all properties but the unwanted one (in this case tel
) of a destructured object in a variable named item
and return in immediately.
In static way:
let list = [
{
id: "27",
order_number: "21251",
tel: 13911111,
weight: "10kg"
},
{
id: "245",
order_number: "223",
tel: 31,
weight: "10kg"
},
{
id: "123",
order_number: "312312321",
tel: 3213123,
weight: "10kg"
}
];
let new_list = list.map(function(obj) {
return {
id: obj.id,
order_number: obj.order_number,
weight: obj.weight
}
});
console.log(list);
console.log(new_list)
This way, you keep both your old array and new array.
If you want to do it in dynamic way, you may use forEach
to check the keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With