-4

Hello I'm trying to remove the actions property from each object within the array data:

[{productName: "", ... action: ...,}, {productName: "", ...action:...} ...]
  • 1
    Duplicate: https://stackoverflow.com/questions/18133635/javascript-remove-attribute-for-all-objects-in-array – Turnip Oct 29 '18 at 18:11

6 Answers6

2
var arr  =[{productName: "bbbb", action: 'b'},
         {productName: "aa",action: 'a'}, 
         {productName: "tt",action: 't'}, 
         {productName: "vv",action: 'v'}]


arr = arr.map((d) => {delete d.action ; return d;});
Abhishek Mani
  • 502
  • 4
  • 12
1

1) With map(...):

your_array.map(o => {'productName': o.productName})

NB that this is more elegant if you want to filter off lots of attributes, but more work if you just want to remove one.

2) With delete:

for (let i = 0; i < your_array.length; i++){
    delete your_array[i].action
}
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • 1
    You're deleting productName in the second one. The first one also removes more than just 'action', which may not be what is wanted. – Blam Oct 29 '18 at 18:10
  • @Blam Nice spot, I've updated the second and added a note to the first. I left the first method as it may be desirable if you just wish to keep one key, value pair of many. – Joe Iddon Oct 29 '18 at 18:14
1

Iterate over the array using map and destructure the object to keep only the required field

var arr = [{
  producet: 'xyz',
  action: 'abc',
  other: 'o'
}, {
  producet: 'xyz',
  action: '123',
  other: 'o'
}, {
  producet: 'xyz',
  action: 'sdf',
  other: 'o'
}]
const result = arr.map(({
  action,
  ...rest
}) => rest);
console.log(result);
Prasun
  • 4,943
  • 2
  • 21
  • 23
1

With ES6 you can use map with destructuring and rest parameters to separate out the object properties you want to retain, and the part you want to discard:

const data = [{
  id: 1,
  productName: "1",
  action: ''
}, {
  id: 1,
  productName: "2",
  action: ''
}];

let out = data.map(({ action, ...rest }) => rest);
console.log(out);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

Use array map It will return a new array.Inside map callback create a new object and populate only those fields that are required. Don't mutate the original array

var arr = [{
  productName: "1",
  action: ''
}, {
  productName: "2",
  action: ''
}];


let newArr = arr.map(function(item) {
  return Object.assign({}, {
    productName: item.productName
  })
});
console.log(newArr)
brk
  • 48,835
  • 10
  • 56
  • 78
0

According to the docs you can use the delete operator.

A simple way to do this is to loop over your array arr and delete the property from each object.

for (var i = 0; i < arr.length; i++){
    delete arr[i].action;
}

This approach is slightly faster than other approaches such as map and for each.

brienna
  • 1,415
  • 1
  • 18
  • 45