将对象的子集直接解构为新对象

时间:2016-09-02 18:53:31

标签: ecmascript-6

是否有一个单行代码可以做到这一点,我在消隐?

// 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

但这似乎让人们在阅读代码时感到困惑,并且需要付出更多努力来弄清楚如何编写代码。

1 个答案:

答案 0 :(得分:0)

_.pick仍然是在ES6中具有用例的Underscore / Lodash功能之一。

ES6 one-liner可能是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 }), {});