gpt4 book ai didi

javascript - lodash 按单个值和数组中的值进行过滤

转载 作者:行者123 更新时间:2023-12-03 03:28:02 28 4
gpt4 key购买 nike

我有一个快速简单的功能,我需要使用 lodash。

let obj = 

{
"AttributeID": "1",
"KeyID": "0",
"Value": "Undefined",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
},
{
"AttributeID": "1",
"KeyID": "1",
"Value": "Tier 1",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
}, {
"AttributeID": "1",
"KeyID": "2",
"Value": "Tier 2",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
}, {
"AttributeID": "1",
"KeyID": "3",
"Value": "Tier 3",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
}, {
"AttributeID": "1",
"KeyID": "4",
"Value": "Tier 4",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
}


let parent = 1;
let children = ['1', '2', '3', '4'];

let test = _.filter(obj, function(item) {
return parseInt(item.AttributeID) === parent && parseInt(item.KeyID) IN[Children];
})

我尝试按特定父 ID 过滤我的对象,并在这些结果中找到 children 数组中所有具有 KeyID 的对象。

更新:

这是我根据所选答案得出的最终结果。如果有更快捷的方法可以通过将其中一些 lodash 方法链接在一起来完成此操作,请告诉我。

let valueObj = {
"id" : "1",
"name": "Joe"
},
{
"id" : "2",
"name": "Bob"
}
let selectedValues = _.map(valueObj, 'id');
let result = _.filter(obj, function(item) {
return item.AttributeID === attributeID && _.includes(selectedValues, item.KeyID);
});

最佳答案

使用lodash#includes方法。如果 children 数组包含字符串值,则不应将 item.KeyID 转换为数字,而只需比较两个字符串:

let test = _.filter(obj, function(item) {
let attrId = parseInt(item.AttributeID);
return attrId === parent && _.includes(children, item.KeyID);
});

关于javascript - lodash 按单个值和数组中的值进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46226572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com