简体   繁体   English

使用reduce,从对象数组中,在对象的数组属性中创建一组元素

[英]Using reduce, from an array of objects, create a set of elements inside the objects' array attributes

Given the following array:给定以下数组:

foos = [
  {
    id: 0,
    bar: ['a','b','c']
  },
  {
    id: 1,
    bar: ['a','b','d']
  },
  {
    id: 2,
    bar: ['a','c']
  },
]

Using reduce , how can I achieve the following?:使用reduce ,我怎样才能实现以下目标?:

bars == ['a','b','c','d']

I've tried:我试过了:

foo.reduce((bars, foo) => bars.add(foo.bar), new Set())

But it results in a set of objects:但它会产生一组对象:

Set { {0: 'a', 1: 'b', 2: 'c'}, {0: 'a', 1: 'b', 2: 'd'}{0: 'a', 1: 'c'}}

And:和:

foos.reduce((bars, foo) => foo.bar.forEach(bar => bars.add(bar)), new Set())

But the forEach has no access to the bars set.但是forEach无法访问bars集。

Instead of creating a Set inside your reduce .而不是在您的reduce中创建一个Set You could just reduce all bar arrays into a single one and pass that to your Set constructor.您可以将所有bar数组减少为一个,并将其传递给您的 Set 构造函数。

 const foos = [ { id: 0, bar: ['a','b','c'] }, { id: 1, bar: ['a','b','d'] }, { id: 2, bar: ['a','c'] }, ]; const bars = new Set(foos.reduce((all, foo) => [...all, ...foo.bar], [])); console.log(...bars);

With flatMap :使用flatMap

 const foos = [ { id: 0, bar: ['a','b','c'] }, { id: 1, bar: ['a','b','d'] }, { id: 2, bar: ['a','c'] }, ]; const bars = new Set(foos.flatMap(foo => foo.bar)); console.log(...bars);

You can concat the bar property in the accumulator, and use .filter method to make the values unique:您可以concatbar在累加器财产,并使用.filter方法做出独特的价值:

 const foos = [{ id: 0, bar: ['a', 'b', 'c'] }, { id: 1, bar: ['a', 'b', 'd'] }, { id: 2, bar: ['a', 'c'] }, ]; const bars = foos .reduce((acc, itm) => acc.concat(itm.bar), []) .filter((i, x, s) => s.indexOf(i) === x); console.log(...bars);

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

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