在ES 6中从对象中获取一些属性的单行 [英] One-liner to take some properties from object in ES 6
问题描述
我已经想出了使用解构+简化对象的解决方案字面上,但我不喜欢代码中重复的列表。
有一个更细微的解决方案吗?
(v)=> {
let {id,title} = v;
return {id,title};
}
不避免重复字段列表。它使用参数解构来避免需要 v
参数。
({id,title})=> ({id,title})
@ EthanBrown的解决方案更为通用。这是一个更为惯用的版本,它使用 Object.assign
和计算属性( [p]
部分) :
function pick(o,... props){
return Object.assign({},.. .props.map(prop =>({[prop]:o [prop]})));
}
如果我们要保留属性的属性,例如可配置
和getter和setter,同时省略不可枚举的属性,然后:
函数pick(o,... props){
var has = p => o.propertyIsEnumerable(p),
get = p => Object.getOwnPropertyDescriptor(o,p);
return Object.defineProperties({},
Object.assign({},... props
.filter(prop => has(prop))
.map(prop =>({prop:get(props)})))
);
}
How one can write a function, which takes only few attributes in most-compact way in ES6?
I've came up with solution using destructuring + simplified object literal, but I don't like that list of fields is repeated in the code.
Is there an even slimmer solution?
(v) => {
let { id, title } = v;
return { id, title };
}
Here's something slimmer, although it doesn't avoid repeating the list of fields. It uses "parameter destructuring" to avoid the need for the v
parameter.
({id, title}) => ({id, title})
@EthanBrown's solution is more general. Here is a more idiomatic version of it which uses Object.assign
, and computed properties (the [p]
part):
function pick(o, ...props) {
return Object.assign({}, ...props.map(prop => ({[prop]: o[prop]})));
}
If we want to preserve the properties' attributes, such as configurable
and getters and setters, while also omitting non-enumerable properties, then:
function pick(o, ...props) {
var has = p => o.propertyIsEnumerable(p),
get = p => Object.getOwnPropertyDescriptor(o, p);
return Object.defineProperties({},
Object.assign({}, ...props
.filter(prop => has(prop))
.map(prop => ({prop: get(props)})))
);
}
这篇关于在ES 6中从对象中获取一些属性的单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!