You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用_.pickBy过滤对象中值数组里序列号以N结尾的元素?

如何用Lodash过滤对象中序列号以"N"结尾的元素?

你现在有这样一个包含客户端文档的对象:

let documents = {
  "A": [{"document":"test1", "serial":"123"}, {"document":"test2", "serial":"456N"}],
  "B": [{"document":"test3", "serial":"789N"}, {"document":"test24", "serial":"012"}]
};

想要得到过滤后的结果,只保留序列号以"N"结尾的元素,最终目标是:

{"A": [{"document":"test2", "serial":"456N"}], "B": [{"document":"test3", "serial":"789N"}]}

你尝试用Lodash的_.pickBy和_.filter组合,但还没完成正确实现,下面来一步步解决这个问题。

正确的Lodash实现方式

这里要注意:_.pickBy是用来筛选对象的键(比如决定保留A还是B这个键),而我们首先需要对每个键对应的数组做元素过滤,所以应该先用_.mapValues遍历每个客户端的文档数组,完成元素过滤后,再根据需求决定是否移除空数组的键。

完整代码如下:

const _ = require('lodash');

let documents = {
  "A": [{"document":"test1", "serial":"123"}, {"document":"test2", "serial":"456N"}],
  "B": [{"document":"test3", "serial":"789N"}, {"document":"test24", "serial":"012"}]
};

// 第一步:对每个客户端的文档数组,过滤出serial以"N"结尾的元素
let filteredByItems = _.mapValues(documents, (docObjs) => {
  return _.filter(docObjs, ({ serial }) => serial.endsWith('N'));
});

// 第二步:(可选)移除过滤后为空数组的客户端键
let result = _.pickBy(filteredByItems, (docs) => docs.length > 0);

console.log(result);

代码细节说明

  • _.mapValues:遍历documents对象的每个值(即每个客户端的文档数组),对数组执行过滤逻辑,返回处理后的新对象。
  • _.filter:在每个文档数组中,用原生String.endsWith('N')快速判断序列号是否符合要求,筛选出符合条件的元素。
  • _.pickBy:如果你的场景中存在某个客户端过滤后没有符合条件的文档(数组为空),这一步可以把这些空数组对应的键从结果中移除,和你想要的示例逻辑完全匹配。

如果能确定所有客户端过滤后至少有一个符合条件的元素,也可以跳过第二步,直接用filteredByItems作为最终结果。

内容的提问来源于stack exchange,提问作者jsh6303

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:25:14