我有一个快速简便的功能,需要使用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筛选对象,然后在这些结果中找到所有在KeyID数组中具有children的对象。

更新:

这是根据所选答案得出的最终结果。如果通过将这些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/

10-16 19:45