Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove specific column from data array (JS)

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?

like image 267
Ian Avatar asked Jan 03 '23 06:01

Ian


2 Answers

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:

  • Any property declared with let or const cannot be deleted from the scope within which they were defined
  • If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).
  • Any property declared with var cannot be deleted from the global scope or from a function's scope.

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.

like image 155
Christopher Francisco Avatar answered Jan 05 '23 16:01

Christopher Francisco


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.

like image 32
tung yu Avatar answered Jan 05 '23 17:01

tung yu