使用lodash在javascript中查找两组数据之间的匹配

时间:2019-02-23 21:47:31

标签: javascript arrays object lodash

我有两个数据列表,我想使用lodashlistA的每个元素与listB的值进行比较。

示例:

var listA = ["Y", "A", "Z", "T"];
var listB = [{id:15467, value:"E"}, {id:23453, value:"A"}, {id:76564, value:"O"}, {id:86543, value:"T"}];

一次在listA上获取一个元素,然后找到listB的匹配值。 如果为true,则返回listB的对象。

result = [{id:23453, value:"A"}, {id:86543, value:"T"}]

希望您能帮助我吗?

4 个答案:

答案 0 :(得分:2)

您可以将_.filter_.includes一起使用。

var listA = ["Y", "A", "Z", "T"],
    listB = [{ id: 15467, value: "E" }, { id: 23453, value: "A" }, { id: 76564, value: "O" }, { id: 86543, value: "T" }],
    result = _.filter(listB, ({ value }) => _.includes(listA, value));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 1 :(得分:1)

尝试一下。过滤所有项目

let listA = ["Y", "A", "Z", "T"];
let listB = [{id:15467, value:"E"}, {id:23453, value:"A"}, {id:76564, value:"O"}, {id:86543, value:"T"}];
let result = [];

listA.map(letter =>{
  for (var i = 0; i < listB.length; i++) {
    if(letter == listB[i].value){
      result.push(listB[i])
    }
  }
})


console.log(result)

答案 2 :(得分:0)

您可以使用filterincludes运算符:

  • “过滤器” listB
  • ...使用谓词功能
  • ...检查listA是否包含value
_.filter(listB, function(listBItem) { 
    return _.includes(listA, listBItem.value);
});

答案 3 :(得分:0)

尽管您可以使用lodash的_.intersectionWith()查找两个数组之间的公分母,但项和顺序将是listB的分母:

const listA = ["Y", "A", "Z", "T"];
const listB = [{ id: 86543, value: "T" }, { id: 15467, value: "E" }, { id: 23453, value: "A" }, { id: 76564, value: "O" }]; // I've moved value: "T" to the start

const result = _.intersectionWith(
  listB, 
  listA,
  (a, b) => a.value === b
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

要获取listB排序的listA中的项目,请使用lodash的_.flow()创建一个函数。将listB设置为键,将_.keyBy()转换为对象(使用value)。提取listA_.at()排序的项目,然后_.reject提取所有未定义的项目:

const { flow, partialRight: pr, keyBy, at, reject, isUndefined } = _;

const fn = paths => flow(
  pr(keyBy, 'value'), // convert listB to an object, with the value as the key
  pr(at, paths), // get the items from the object ordered by listA
  pr(reject, isUndefined) // remove undefined items
);

const listA = ["Y", "A", "Z", "T"];
const listB = [{ id: 86543, value: "T" }, { id: 15467, value: "E" }, { id: 23453, value: "A" }, { id: 76564, value: "O" }];

const result = fn(listA)(listB);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>