将对象的子集直接分解为新对象 [英] Destructuring a subset of an object directly into a new object
本文介绍了将对象的子集直接分解为新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个单行代码可以执行此操作?
Is there a one-liner to do this that I'm blanking on?
// 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
我能想到的唯一方法是:
The only way I can think of is:
var {keyIDontWant, otherUnwanted, ...goodKeys} = this.state
但是,这似乎会使阅读代码的人感到困惑,并花更多的精力弄清楚如何编写。
But this seems like it would be confusing to people reading the code, and take more effort to figure out how to write.
推荐答案
_。pick
仍然是在ES6中有用例的Underscore / Lodash功能之一。
_.pick
is still one of Underscore/Lodash features that have their use cases in ES6.
ES6单线可能是IIFE并将导致两次枚举属性列表:
ES6 one-liner may be an IIFE and will result in enumerating the list of properties twice:
let goodKeys = (
({toDate, fromDate, location, flavor}) => ({toDate, fromDate, location, flavor})
)(this.state);
ES.next-lineer对应的 _。pick
可能涉及 Object.entries
:
ES.next one-liner counterpart to _.pick
may involve Object.entries
:
Object.entries(o)
.filter(([key]) => ['toDate', 'fromDate', 'location', 'flavor'].includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});
这篇关于将对象的子集直接分解为新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文