从数组中删除所有对象的属性

249
我想从数组中的每个对象中删除“bad”属性。是否有比使用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;
}

感觉应该有一种方法可以使用 prototype,或者其他的什么东西。我不知道。有什么想法吗?


1
无论如何,其他方法都不能获得比线性O(n)更少的时间复杂度。无论你使用什么方法,都需要访问数组中的所有元素。 - Brian
1
@Bergi 我想知道他们是指PrototypeJS还是Array原型,dystroy举例说明了什么。 - Ian
我不确定在循环之前将数组长度存储在变量中是否明智。如果进行性能分析,您肯定会发现这样做不值得痛苦。 - Denys Séguret
@dystroy 除了再创建一个本地变量,还有什么“痛点”吗? - Ian
1
@ZackArgyle 是的,在一般情况下没有比这更快的了。 - Denys Séguret
显示剩余3条评论
19个回答

3
这个问题现在有点老了,但我想提供一种替代方案,它不会改变源数据,并且需要最少的手动操作:
function mapOut(sourceObject, removeKeys = []) {
  const sourceKeys = Object.keys(sourceObject);
  const returnKeys = sourceKeys.filter(k => !removeKeys.includes(k));
  let returnObject = {};
  returnKeys.forEach(k => {
    returnObject[k] = sourceObject[k];
  });
  return returnObject;
}

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

const newArray = array.map(obj => mapOut(obj, [ "bad", ]));

这还不太完美,但是保持了一定的不可变性,并且具有命名多个要删除的属性的灵活性。(欢迎提出建议)


1

这对我很有效!

export function removePropertiesFromArrayOfObjects(arr = [], properties = []) {
return arr.map(i => {
    const newItem = {}
    Object.keys(i).map(key => {
        if (properties.includes(key)) { newItem[key] = i[key] }
    })
    return newItem
})
}

1
我建议在 forEach() 循环中使用 Object.assign,这样对象就会被复制,而不会影响原始的对象数组。
var res = [];
array.forEach(function(item) { 
    var tempItem = Object.assign({}, item);
    delete tempItem.bad; 
    res.push(tempItem);
});
console.log(res);

1

ES6:

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

0
如果您正在使用underscore.JS库:
let asdf = [{"asd": 12, "asdf": 123}, {"asd": 121, "asdf": 1231}, {"asd": 142, "asdf": 1243}]


_.map(asdf, function (row) {
    return _.omit(row, ['asd'])
})

0
通用函数,用于移除对象数组中所有对象的属性:

/**
 * Returns the array of objects without the indicated property.
 * @param {array} arrayOfObjects
 * @param {string} property
 * @returns {array}
 * @see https://dev59.com/MmMl5IYBdhLWcg3wyJYe#69723902 remove property from an array of objects
 * @see https://github.com/airbnb/javascript#objects--rest-spread new object with certain properties omitted
 */
const removePropertyFromArrayOfObjects = (arrayOfObjects, property) => {
    return arrayOfObjects.reduce((accumulator, currentValue) => {
        const {[property]: _new_name_, ...keep_data} = currentValue;
        accumulator.push(keep_data);
        return accumulator;
    }, []);
};


// Example of use:

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

console.log(removePropertyFromArrayOfObjects(array, "bad"));

// Expected output: Array [Object { good: "something" }, Object { good: "something" }]


0

通过 reduce:

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

0

有很多库可供选择。这完全取决于您的数据结构有多复杂(例如,请考虑深度嵌套的键)

我们喜欢object-fields,因为它还可以处理深度嵌套的层次结构(用于API字段参数构建)。以下是一个简单的代码示例

// const objectFields = require('object-fields');

const array = [ { bad: 'something', good: 'something' }, { bad: 'something', good: 'something' } ];

const retain = objectFields.Retainer(['good']);
retain(array);
console.log(array);
// => [ { good: 'something' }, { good: 'something' } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-fields@2.0.19"></script>

免责声明:本人是object-fields的作者。


-5

var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"}];
var results = array.map(function(item){
  return {good : item["good"]}
});
console.log(JSON.stringify(results));


你能解释一下你的解决方案吗? - sg7
Map是JavaScript ES6中的一种新数据结构。附上的链接可能会对您有所帮助。https://hackernoon.com/what-you-should-know-about-es6-maps-dc66af6b9a1e - hk_y
如果您的项目中有很多道具,则此解决方案并不好。 - Robdll
是的!尝试提供不同的方法。 - hk_y
在你的评论中,你混淆了你没有使用的数据结构Map和你正在使用的数组方法Array.prototype.map - Emile Bergeron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接