单行从 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)})))
    );
}

相关文章