【问题标题】:Data manipulation with loadash (sort of join left)使用 loadash 进行数据操作(左连接)
【发布时间】:2016-11-27 10:14:15
【问题描述】:

this post on SO之后,我想用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 underscore.js lodash


【解决方案1】:

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

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

使用find 从现金流返回每个月的值。如果没有找到现金流,那么get 将使用默认值,这里是空字符串。

【讨论】:

  • 最好的解决方案,因为它使用了 lodash。我学过 .chain、.get 和 .find,谢谢
【解决方案2】:

在纯 Javascript 中,您可以对给定数据使用哈希表并根据 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; }

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    相关资源
    最近更新 更多