是否有一个单行代码可以做到这一点,我在消隐?
// 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
但这似乎让人们在阅读代码时感到困惑,并且需要付出更多努力来弄清楚如何编写代码。
答案 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 }), {});