Does an ES6 shorthand exist for copying a subset of an object's properties into a new object? [duplicate]

旧巷老猫 提交于 2020-12-06 04:21:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!