简体   繁体   English

ES6中的简单解构数组/对象

[英]Simple destructuring Array/Object in ES6

I am trying to return new object with selected keys - reqProps . 我试图返回具有选定键-reqProps的新对象。 I managed to do it with fixes props prop1, prop3 and now want to be able to pass reqProps array values to replace prop1, prop3. 我设法通过修复props prop1, prop3做到了,现在我希望能够传递reqProps数组值来替换prop1,prop3。 I tried function, and string literals and few 'hacks'. 我尝试了函数,字符串文字和一些“ hacks”。 None of them worked 他们都没有工作

const data = [
  {
    prop1: 1,
    prop2: 2,
    prop3: 3
  },
  {
    prop1: 10,
    prop2: 20,
    prop3: 30
  },
  {
    prop2: 200,
    prop4: 400
  },
  {
    prop3: 3000
  }
];

// to return properties for the following...
const reqProps = ['prop2','prop3','prop4'];

// current implementation fixing return object with prop1, prop3
const obj = data.map(({prop1, prop3}) => {
    return {prop1, prop3};
});

The result of obj for the moment is 目前, obj的结果是

[{"prop1":1,"prop3":3},{"prop1":10,"prop3":30},{},{"prop3":3000}]

I do not want to use loops, quite like the 'power' of destructuring! 我不想使用循环,就像解构的“力量”一样! ;) ;)

If you insist on destructuring, you have to use eval : 如果您坚持要进行销毁,则必须使用eval

const reqProps = ['prop2','prop3','prop4'];

const literalString = '{'+reqProps.join(',')+'}';

const obj = data.map(new Function(literalString, 'return '+literalString));

You really should use a loop - you can also hide it in a helper function or just use reduce . 您确实应该使用循环-您也可以将其隐藏在辅助函数中,也可以只使用reduce

As @Bergi suggests, you'd better use loops in some way. 正如@Bergi所建议的,您最好以某种方式使用循环。

Here's a variant with implicit loops: 这是带有隐式循环的变体:

data.map(o => reqProps.filter(p => p in o)
                      .reduce((acc, p) => ({...acc, [p]: o[p]}), {}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM