javascript - 在具有复杂条件的两个对象数组之间检索项目
问题描述
我有两个对象列表:
let list1 = [{id: '1', status: 'use', comment: 'xxxx'}, {id: '2', status: 'ready', comment: 'yyyy'}, {id: '3', status: 'ready', comment: 'zzzz'}];
let list2 = [{uid: '1', elec: 60}, {uid: '2', elec: 60}, {uid: '10', elec: 60}, {uid: '3', elec: 40}];
我想要的是检索具有 elec > 50 且与 list1 的一个项目 id 相同的 uid 的 list2 对象,仅当 list1 的项目具有状态 ==“准备好”时。另外,我想将来自 list1 对象的参数“comment”添加到此项。
在这个例子中,我的结果值是:{uid: '2',lect: 60, comment: 'yyyy'}。
我这样做了:
let list1Filtered = list1.filter(itemList1 => itemList1.status == 'ready');
let list2Filtered = list2.filter(itemList2 => itemList2.elec > 50);
var result;
for ( let itemList1Filtered of list1Filtered ) {
for ( let itemList2Filtered of list2Filtered ) {
if (!result && itemList1Filtered.id == itemList2Filtered.uid) {
result = itemList2Filtered;
result.comment = itemList1Filtered.comment;
}
}
}
return result;
我想知道在 Javascript 中是否有更优雅和/或更复杂的方法来执行此操作。
解决方案
let result = {
...list2.filter(
a => a.elec > 50 && a.uid === list1.filter(b => b.status === "ready")[0].id)[0],
comments: list1.filter(b => b.status === "ready")[0].comment
}
推荐阅读
- python - 当我插入新数据时,是否需要在 NodeJS 中刷新我的 Sqlite3 数据库?
- assembly - MIPS:接受用户输入值并使用循环计算指数的程序
- python - Pyspark - 用空条件替换值
- java - Hibernate 5.3.10 一对多 insertable = false 的行为与 Hibernate 5.2.1 不同
- javascript - 使用纯 JS 每 x 秒添加 CSS 动画?
- ios - 方法 scrollToItemAtIndexPath 不适用于 iOS 14
- r - 按多个组对特定行求和
- linux - cpu 如何向内核发送有关硬件异常的信号?
- r - R:根据另一列的值对一列中的值进行分箱
- haskell - Haskell 解析令牌输入条件