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

RnR*_*ger 2 javascript reduce set

给定以下数组:

foos = [
  {
    id: 0,
    bar: ['a','b','c']
  },
  {
    id: 1,
    bar: ['a','b','d']
  },
  {
    id: 2,
    bar: ['a','c']
  },
]
Run Code Online (Sandbox Code Playgroud)

使用reduce,我怎样才能实现以下目标?:

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

我试过了:

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

但它会产生一组对象:

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

和:

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

forEach无法访问该bars集合。

Rey*_*yno 5

而不是在你的reduce中创建一个Set。您可以将所有数组简化为一个数组并将其传递给 Set 构造函数。bar

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);
Run Code Online (Sandbox Code Playgroud)

使用平面地图

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);
Run Code Online (Sandbox Code Playgroud)