我想从数组中的每个对象中删除坏属性。有没有比使用for循环并从每个对象中删除它更好的方法呢?

var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"},...];

for (var i = 0, len = array.length; i < len; i++) {
  delete array[i].bad;
}

似乎应该有一种方法来使用原型之类的。我不知道。想法吗?


当前回答

通过减少:

const newArray = oldArray.reduce((acc, curr) => {
  const { remove_one, remove_two, ...keep_data } = curr;
  acc.push(keep_data);
  return acc;
}, []);

其他回答

外面有很多图书馆。这完全取决于你的数据结构有多复杂(例如,考虑深度嵌套的键)

我们喜欢对象字段,因为它也适用于深度嵌套的层次结构(build for api fields参数)。下面是一个简单的代码示例

// const objectFields = require('object-fields'); Const array = [{bad: 'something', good: 'something'}, {bad: 'something', good: 'something'}]; const retain = objectfields . retain (['good']); 保留(数组); console.log(数组); // => [ { 好:“东西”},{好:‘东西’}] .as-console-wrapper {max-height: 100% !重要;上图:0} < script src = " https://bundle.run/object-fields@2.0.19 " > < /脚本>

免责声明:我是对象字段的作者

数组var =[{“坏”:“东西”,“好”:“东西”},{“坏”:“东西”,“好”:“东西”}); const cleanArray = array.map(item=>{ 删除item.bad 返回项目 }) console.log (cleanArray)

通过减少:

const newArray = oldArray.reduce((acc, curr) => {
  const { remove_one, remove_two, ...keep_data } = curr;
  acc.push(keep_data);
  return acc;
}, []);

ES6:

const newArray = array.map(({keepAttr1, keepAttr2}) => ({keepAttr1, newPropName: keepAttr2}))

只有当你的对象相似时,使用原型的解决方案才有可能:

function Cons(g) { this.good = g; }
Cons.prototype.bad = "something common";
var array = [new Cons("something 1"), new Cons("something 2"), …];

但它很简单(和O(1)):

delete Cons.prototype.bad;