我有两个数据列表,我想使用lodash将listA
的每个元素与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"}]
希望您能帮助我吗?
答案 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)
您可以使用filter
和includes
运算符:
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>