javascript - 我想将两个 Javascript array 与 Lodash ( 非 concat ) 结合起来

  显示原文与译文双语对照的内容
69 4

我有两个 array 像 below

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

我希望他们能像这样

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' }
];

我认为在这个例子中有一个正确的Lodash 功能,但我自己找不到。有什么很酷的小丑能帮助你走出这个地狱。感谢~

时间:原作者:0个回答

75 1

我同意使用插件,而不是重写人们提供的内容。但是当使用一个插件时,使用一个插件变得更加复杂,最好使用 simplier soluce 。

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);
原作者:
57 4

一个方法是减少+ forEach,但任何双循环都应该工作。

const registers = [{ user: 'Allen', type: 'phone' }, { user: 'Eric', type: 'email' }];
const dates = ['20171225', '20180914'];
let answer = registers.reduce((acc, n) => {
 dates.forEach(x => {
 acc.push({user: n.user, type: n.type, date: x});
 });
 return acc;
 }, [])
 console.log(answer);
原作者:
83 1

在这种情况下,使用 lodash 不会产生太多的代码还原( 你可以简单地用 a.map(...) 替换对 _.map(a,.. .)的调用) 。但是,这里是:

const registers = [{ user: 'Allen', type: 'phone' }, { user: 'Eric', type: 'email' }];
const dates = ['20171225', '20180914'];
const result = _.map(registers, ({ user, type }) => _.map(dates, (date) => ({ user, type, date })));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>
原作者:
65 1

就像使用lodash所声明的那样,这里有一个解决方案

Lodash变种

var registers = [{ user: 'Allen', type: 'phone' }, { user: 'Eric', type: 'email' }];
var dates = ['20171225', '20180914'];
let result = _.map(registers, function(value, index, _source){
 return _.extend(value, { date: (dates[index] || null)});
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>

Vanilla变种

var registers = [{ user: 'Allen', type: 'phone' }, { user: 'Eric', type: 'email' }];
var dates = ['20171225', '20180914'];
let result = registers.map(function(value, index, _source){
 return Object.assign(value, { date: (dates[index] || null)});
});
console.log(result);
原作者:
148 0

使用 array.prototype.mapspread 运算符

 var registers = [{ user: 'Allen', type: 'phone' }, { user: 'Eric', type: 'email' }];
 var dates = ['20171225', '20180914'];
 var res = [].concat(...dates.map(date => registers.map(r => (r.date = date, r))));
 console.log(res);
原作者:
...