Return 使用 es6 映射解构对象中的数组

Return deconstructed array in object with es6 map

我想 return 一个解构的数组,所以我只在 returned 数组而不是数组中得到单个元素。

const data = [
 {
    title: 'amsterdam',
    components: [
      {
        id: 1,
        name: 'yanick',    
      },
      {
        id: 2,
        name: 'ronald',    
      },
    ],  
  },
  
  {
    title: 'rotterdam',
    components: [
      {
        id: 4,
        name: 'nicky',    
      },
      {
        id: 3,
        name: 'casper',    
      },
    ],  
  },
];

const test = data
  .map(item => {
    console.log(item.components);
    return item.components;
  }).map(array => {
   // how to get comibned components here?
    // it can't use ...item.components (deconstructing or something)
  });
  
console.log('test', test);

所以我想使用链式映射函数创建一个包含 item.components 中所有元素的数组。这可能吗?好像不能解构每一项的数组。

Array.prototype.reduce 似乎是在这种情况下使用的正确方法。

const test = data.reduce( (result, current) => result.concat(current.components) , []);

console.log('test', test);

输出

test [ { id: 1, name: 'yanick' },
  { id: 2, name: 'ronald' },
  { id: 4, name: 'nicky' },
  { id: 3, name: 'casper' } ]

要将数据合并到单个数组中,您可以将 reduceconcat 结合使用,这将创建单个结果数组。

const data = [
 {
    title: 'amsterdam',
    components: [
      {
        id: 1,
        name: 'yanick',
      },
      {
        id: 2,
        name: 'ronald',
      },
    ],
  },

  {
    title: 'rotterdam',
    components: [
      {
        id: 4,
        name: 'nicky',
      },
      {
        id: 3,
        name: 'casper',
      },
    ],
  },
];

const test = data
  .map(item => {
    return item.components;
  }).reduce((res, item) => {
    return res.concat(item);
  }, []);

console.log('test', test);

Array.map(), and flatten by spreading into Array.concat() 获得 components:

const data = [{"title":"amsterdam","components":[{"id":1,"name":"yanick"},{"id":2,"name":"ronald"}]},{"title":"rotterdam","components":[{"id":4,"name":"nicky"},{"id":3,"name":"casper"}]}];

const result = [].concat(...data.map(o => o.components));

console.log(result);