单行从 ES 6 中的对象获取一些属性 [英] One-liner to take some properties from object in ES 6

查看:25
本文介绍了单行从 ES 6 中的对象获取一些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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})

(See a runnable example in this other answer).

@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆