使用 lodash 进行数据操作(左连接)

Data manipulation with loadash (sort of join left)

之后,我想用lodash实现最简单的数据操作

但是我真的不知道怎么做。

I've set a Jsfiddle here.

问题:

var months = ["jan", "feb", "mar", "apr"];
var cashflows = [
    {'month':'jan', 'value':10}, 
  {'month':'mar', 'value':20}
  ];

我要:

[
  {'month':'jan', 'value':10},
  {'month':'feb', 'value':''},
  {'month':'mar', 'value':20},
  {'month':'apr', 'value':''}
];

注意:为了提高可读性,我想要对losash函数调用较少的解决方案。

在普通 Javascript 中,您可以对给定数据使用哈希 table 并根据 months 顺序重建结果。

var months = ['jan', 'feb', 'mar', 'apr'],
    cashflows = [{ month: 'jan', value: 10 }, { month: 'mar', value: 20 }],
    result = months.map(function (m) {
        return this[m] || { month: m, value: '' };
    }, cashflows.reduce(function (r, a) {
        r[a.month] = a;
        return r;
    }, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这是一个 lodash 解决方案,maps 在月数组上创建你想要的结构:

var result = _.map(months, function(month){
    return {
        month: month,
        value: _.chain(cashflows)
            .find({month: month})
            .get('value', '')
            .value();
    }
});

使用find. If no cashflow is found then get从现金流返回的每个月的值将使用默认值,此处为空字符串。