如何在 JavaScript 中省略对象的特定属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43011742/
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-08-23 01:36:08  来源:igfitidea点击:

How to omit specific properties from an object in JavaScript

javascriptecmascript-6

提问by Aweb

Is there a clean way to return a new object that omits certain properties that the original object contains without having to use something like lodash?

有没有一种干净的方法来返回一个新对象,该对象省略原始对象包含的某些属性,而不必使用诸如 lodash 之类的东西?

回答by Craig Gehring

const { bar, baz, ...qux } = foo

Now your object quxhas all of the properties of fooexcept for barand baz.

现在您的对象qux具有foobarand之外的所有属性baz

回答by gyre

If you know the list of the properties that you want preservedas well as omitted, the following "whitelisting" approach should work:

如果您知道要保留和省略的属性列表,则应使用以下“白名单”方法:

const exampleFilter = ({ keepMe, keepMeToo }) => ({ keepMe, keepMeToo })

console.log(
  exampleFilter({
    keepMe: 'keepMe',
    keepMeToo: 'keepMeToo',
    omitMe: 'omitMe',
    omitMeToo: 'omitMeToo'
  })
)

回答by Brigand

There's the blacklistpackage on npm which has a very flexible api.

还有的blacklist具有非常灵活的API上NPM包。

Also a situational trick using the object rest-spread proposal (stage-3).

也是使用对象休息传播建议(第 3 阶段)的情境技巧。

const {a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4};
a // 1
b // 2
rest // {c: 3, d: 4}

This is often used in react components where you want to use a few properties and pass the rest as props to a <div {...props} />or similar.

这通常用于反应组件中,您希望使用一些属性并将其余属性作为道具传递给 a<div {...props} />或类似的。

回答by Eddie Cooro

In modern environments you can use this code snippet:

在现代环境中,您可以使用以下代码片段:

function omit(key, obj) {
  const { [key]: omitted, ...rest } = obj;
  return rest;
}

回答by Geoffrey Hale

const {omittedPropertyA, omittedPropertyB, ...remainingObject} = originalObject;


Explanation:

解释:

With ES7

使用 ES7

you could use object destructuringand the spread operatorto omit properties from a javascript object:

您可以使用对象解构扩展运算符来省略 javascript 对象的属性:

const animalObject = { 'bear': 1, 'snake': '2', 'cow': 3 };

const {bear, ...other} = animalObject

// other is: { 'snake': '2', 'cow:'  3}

source: https://remotedevdaily.com/two-ways-to-omit-properties-from-a-javascript-object/

来源:https: //remotedevdaily.com/two-ways-to-omit-properties-from-a-javascript-object/

回答by will Farrell

Omit and array of keys, using ES7 w/ recursion.

使用带有递归的 ES7 省略键和键数组。

function omit(keys, obj) {
  if (!keys.length) return obj
  const { [keys.pop()]: omitted, ...rest } = obj;
  return omit(keys, rest);
}

This builds on top of @Eddie Cooro answer.

这是建立在@Eddie Cooro 回答之上的。

回答by ghiles ybeggazene

const x = {obj1: 1, obj2: 3, obj3:26};


const {obj1,obj2, ...rest} = x;
console.log(rest)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>

回答by guest271314

You can use Object.assign(), delete

您可以使用 Object.assign(),删除

var not = ["a", "b"]; // properties to delete from obj object
var o = Object.assign({}, obj);
for (let n of not) delete o[n];

Alternatively

或者

var props = ["c", "d"];
let o = Object.assign({}, ...props.map(prop => ({[prop]:obj[prop]})));

回答by Andrés Andrade

function omitKeys(obj, keys) {
        var target = {}; 

        for (var i in obj) { 
            if (keys.indexOf(i) >= 0) continue;
            if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; 

            target[i] = obj[i]; 
        } 

        return target; 
    }

回答by rorymorris89

Sure, why not something like:

当然,为什么不是这样的:

var original = {
  name: 'Rory',
  state: 'Bored',
  age: '27'
};

var copied = Object.assign({}, original);
delete copied.age;

console.log(copied);

https://jsfiddle.net/4nL08zk4/

https://jsfiddle.net/4nL08zk4/