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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18133635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:50:23  来源:igfitidea点击:

Remove property for all objects in array

javascriptjavascript-objects

提问by Zack Argyle

I want to remove the badproperty from every object in the array. Is there a better way to do it than using a forloop and deleting it from every object?

我想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;
}

Just seems like there should be a way to use prototype, or something. I don't know. Ideas?

似乎应该有一种方法可以使用prototype,或其他东西。我不知道。想法?

回答by piotr_cz

With ES6, you may deconstruct each object to create new one without named attributes:

使用 ES6,您可以解构每个对象以创建没有命名属性的新对象:

const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)

回答by Denys Séguret

The only other ways are cosmetic and are in fact loops.

唯一的其他方式是装饰性的,实际上是循环。

For example :

例如 :

array.forEach(function(v){ delete v.bad });

Notes:

笔记:

  • if you want to be compatible with IE8, you'd need a shim for forEach. As you mention prototype, prototype.js also has a shim.
  • deleteis one of the worst "optimization killers". Using it often breaks the performances of your applications. You can't avoid it if you want to really remove a property but you often can either set the property to undefinedor just build new objects without the property.
  • 如果你想与 IE8 兼容,你需要一个 forEach 的垫片。正如你提到的原型,prototype.js 也有一个 shim
  • delete是最糟糕的“优化杀手”之一。使用它通常会破坏应用程序的性能。如果您想真正删除属性,则无法避免它,但您通常可以将属性设置为undefined或仅构建没有该属性的新对象。

回答by ex0b1t

I prefer to use map to delete the property and then return the new array item.

我更喜欢使用 map 删除属性,然后返回新的数组项。

array.map(function(item) { 
    delete item.bad; 
    return item; 
});

回答by Cody

If you use underscore.js:

如果你使用underscore.js

var strippedRows = _.map(rows, function (row) {
    return _.omit(row, ['bad', 'anotherbad']);
});

回答by Bergi

A solution using prototypes is only possible when your objects are alike:

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

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

But then it's simple (and O(1)):

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

delete Cons.prototype.bad;

回答by maplemap

For my opinion this is the simplest variant

在我看来,这是最简单的变体

array.map(({good}) => ({good}))

回答by James Marks

This question is a bit old now, but I would like to offer an alternative solution that doesn't mutate source data and requires minimal manual effort:

这个问题现在有点老了,但我想提供一个不改变源数据并且需要最少手动工作的替代解决方案:

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", ]));

It's still a little less than perfect, but maintains some level of immutability and has the flexibility to name multiple properties that you want to remove. (Suggestions welcome)

它仍然不够完美,但保持了一定程度的不变性,并且可以灵活地命名要删除的多个属性。(欢迎提出建议)

回答by Sunali Bandara

i have tried with craeting a new object without deleting the coulmns in Vue.js.

我尝试在不删除 Vue.js 中的库姆斯的情况下创建一个新对象。

let data =this.selectedContactsDto[];

let data =this.selectedContactsDto[];

//selectedContactsDto[] = object with list of array objects created in my project

//selectedContactsDto[] = 包含在我的项目中创建的数组对象列表的对象

console.log(data); let newDataObj= data.map(({groupsList,customFields,firstname, ...item }) => item); console.log("newDataObj",newDataObj);

控制台日志(数据);让 newDataObj= data.map(({groupsList,customFields,firstname, ...item }) => item); console.log("newDataObj",newDataObj);

回答by Ankit Agarwal

I will suggest to use Object.assignwithin a forEach()loop so that the objects are copied and does not affect the original array of objects

我建议Object.assignforEach()循环中使用,以便复制对象并且不影响对象的原始数组

var res = [];
array.forEach(function(item) { 
    var tempItem = Object.assign({}, item);
    delete tempItem.bad; 
    res.push(tempItem);
});
console.log(res);

回答by hk_y

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));