问题
Consider the following object:
const obj = {a: 1, b: 2, c: 3, d: 4, e: 5}
Is there a simple syntax for creating a new object that contains:
const obj2 = {a, b, d}
I'm aware that underscore & lodash have .pick()
, but I'm hoping there's some kind of destructuring trickery that I may not be aware of.
回答1:
Concise one-liner in ES2015 is
const obj2 = (({a, b, d}) => ({a, b, d}))(obj);
It doesn't seem to be possible to avoid {a, b, d}
tautology while keeping it compact at the same time.
回答2:
You can do it in two steps:
const obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
var {a, b, d} = obj;
const obj2 = {a, b, d};
If you don't want to pollute the scope,
const obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
const obj2 = {};
{
let {a, b, d} = obj;
Object.assign(obj2, {a, b, d});
}
回答3:
You could use Rest parameters and create custom pick function like this
const obj = {a: 1, b: 2, c: 3, d: 4, e: 5}
function pick(object, ...p) {
return p.reduce((o, e) => {return o[e] = object[e], o}, {});
}
console.log(pick(obj, 'a', 'b', 'd'))
来源:https://stackoverflow.com/questions/37929175/does-an-es6-shorthand-exist-for-copying-a-subset-of-an-objects-properties-into