Search code examples
javascriptarrayschain

Return deconstructed array in object with es6 map


I want to return a deconsturcted array so I only get single element in te returned array instead of array.

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);

So I want to use chained map functions to create one array of all elements in item.components. Is this possible? Seems like I can't deconstruct the array of each item.


Solution

  • Array.prototype.reduce seems like the correct method to use in this context.

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

    Output

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