[英]How to remove an element from array of literal objects
您好,我正在尝试从数组数据中的每个对象中删除操作属性:
[{productName: "", ... action: ...,}, {productName: "", ...action:...} ...]
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;});
1) With map(...)
: 1) 使用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
: 2) delete
:
for (let i = 0; i < your_array.length; i++){
delete your_array[i].action
}
Iterate over the array using map
and destructure the object to keep only the required field使用map
遍历数组并解构对象以仅保留所需字段
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);
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:在 ES6 中,您可以使用带有解构和休息参数的map
来分离您想要保留的对象属性和您想要丢弃的部分:
const data = [{ id: 1, productName: "1", action: '' }, { id: 1, productName: "2", action: '' }]; let out = data.map(({ action, ...rest }) => rest); console.log(out);
Use array map
It will return a new array.Inside map
callback create a new object and populate only those fields that are required.使用数组map
它将返回一个新数组。内部map
回调创建一个新对象并仅填充那些必需的字段。 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)
According to the docs you can use the delete
operator.根据文档,您可以使用delete
运算符。
A simple way to do this is to loop over your array arr
and delete the property from each object.一个简单的方法是循环遍历数组arr
并从每个对象中删除属性。
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
.这种方法比其他方法(例如map
和for each
)略快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.