首页 > 解决方案 > 在具有复杂条件的两个对象数组之间检索项目

问题描述

我有两个对象列表:

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 中是否有更优雅和/或更复杂的方法来执行此操作。

标签: javascriptarraystypescriptperformanceoptimization

解决方案


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
}


推荐阅读