Search code examples
javascriptarrayslodash

I want to combine two Javascript Array with Lodash (not concat)


I have two array like below

  const registers = [{ user: 'Allen', type: 'phone' }, { user: 'Eric', type: 'email' }];
  const dates = ['20171225', '20180914'];

and I want they comebine like this

const result = [
  { user: 'Allen', type: 'phone', date: '20171225' }
  { user: 'Allen', type: 'phone', date: '20180914' }
  { user: 'Eric', type: 'email', date: '20171225' }
  { user: 'Eric', type: 'email', date: '20180914' }
];

I think there is an proper function of Lodash to use in this case, but I can't find it by myself. Is there any cool geek can help to get out of this hell. Thanks~


Solution

  • I agree to use of plugins instead of rewrite what people have made available. But when It's simple, using a plugin is complicating things, it's better to use the simplier soluce when there is one.

    const registers = [{
      user: 'Allen',
      type: 'phone',
    }, {
      user: 'Eric',
      type: 'email',
    }];
    
    const dates = [
      '20171225',
      '20180914',
    ];
    
    const arr = registers.reduce((tmp, x) => [
      ...tmp,
    
      ...dates.map(y => ({
        ...x,
    
        date: y,
      })),
    ], []);
    
    console.log(arr);