【问题标题】:Data manipulation with Lodash chaining or functional JS challenge使用 Lodash 链接或函数式 JS 挑战的数据操作
【发布时间】:2019-06-04 23:15:42
【问题描述】:

我有一组数据

const allNumbers = [
    { type: "smallNumbers", numbers: [1, 2, 3] },
    { type: "bigNumbers", numbers: [4, 5, 6] }
];

需要成型的

[[1], [2], [3], [4, 5, 6]]

smallNumbers 类型的对象中的数字每个都单独包装在一个数组中,bigNumbers 类型的对象中的数字保持原样。

我将如何使用 Lodash 链接(如果可能)或普通函数式 JS 来做到这一点?

【问题讨论】:

    标签: javascript lodash data-manipulation


    【解决方案1】:

    您可以使用_.flatMap() 来迭代对象,并使用_.chunks()(默认块大小为1)将smallNumbers 拆分为子数组:

    const allNumbers = [
      { type: "smallNumbers", numbers: [1, 2, 3] },
      { type: "bigNumbers", numbers: [4, 5, 6] }
    ];
    
    const result = _.flatMap(allNumbers, ({ type, numbers }) => 
      _.eq(type, 'smallNumbers') ? _.chunk(numbers) : [numbers]
    );
    
    console.log(JSON.stringify(result));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-18
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多