解构的对象的子集直接进入一个新的对象[复制](Destructuring a subset of a

2019-09-29 18:21发布

这个问题已经在这里有一个答案:

  • 单行采取从对象的一些性质在ES 6个 11答案

是否有一个班轮可以做到这一点,我消隐?

// this.state is a basic object with many keys
var {toDate, fromDate, location, flavor} = this.state
var goodKeys = {toDate, fromDate, location, flavor}
// goodKeys is an object that contains a subset of this.state's keys

我能想到的是唯一的方法:

var {keyIDontWant, otherUnwanted, ...goodKeys} = this.state

但是,这似乎将是令人困惑的人阅读的代码,并采取更多的努力弄清楚怎么写。

Answer 1:

_.pick仍然是在他们的ES6用例下划线/ Lodash特征之一。

ES6单行可以是IIFE,并且将导致在列举的属性列表两次:

let goodKeys = (
  ({toDate, fromDate, location, flavor}) => ({toDate, fromDate, location, flavor})
)(this.state);

ES.next一个班轮对口_.pick可能涉及Object.entries

Object.entries(o)
.filter(([key]) => ['toDate', 'fromDate', 'location', 'flavor'].includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});


文章来源: Destructuring a subset of an object directly into a new object [duplicate]