使用过滤器查找匹配的键和值

时间:2018-02-09 18:28:49

标签: javascript

我需要检查json中是否存在键值对。

filter: {department_Id: 20}
tk: {department_Id: 22, timekeeper_Name: "Tesvtda", office_Id: 2, position_Id: 1}

我可以检查对象中是否存在过滤器密钥:

return tk.hasOwnProperty(Object.keys(filter)) ;

但是,我现在如何检查价值呢?

全功能:

filteredTimekeeperList: function() {
  return this.timekeepersList.filter(tk => {
    return this.filters.forEach(filter => {
      console.log(filter, tk);
      console.log(tk.hasOwnProperty(Object.keys(filter)));
      return tk.hasOwnProperty(Object.keys(filter)) ; // True, now I need to return if both are matches
    });
  });
}

示例:https://codesandbox.io/s/y3xqo51wqv

Input:
 timekeepersList: [
        {
          department_Id: 20,
          timekeeper_Name: "Test",
          office_Id: 1,
          position_Id: 1
        },
        {
          department_Id: 20,
          timekeeper_Name: "Test",
          office_Id: 1,
          position_Id: 1
        },
        {
          department_Id: 21,
          timekeeper_Name: "Test",
          office_Id: 1,
          position_Id: 1
        }
      ],
      filters: [
        {
          department_Id: 21
        }
      ]

Output: 
        {
          department_Id: 21,
          timekeeper_Name: "Test",
          office_Id: 1,
          position_Id: 1
        }

1 个答案:

答案 0 :(得分:2)

你可以这样做:

如果给定键的值与filters数组对象的值匹配,则想要过滤timeKeepersList。这是.some().every()非常方便的地方。

使用.every()将确保filters数组中每个对象中的每个键都与给定计时器的键匹配。如果来自.some()数组中任何对象的任何键与计时器的匹配,则使用filters将返回给定的计时器。

根据您的情况,您也可以明显地混合和匹配它们。如果要在任何对象与所有键匹配的情况下返回计时器,或者所有对象都与任何键匹配。这些案例分别为.some() -> .every().every() -> .some()

var timekeepersList = [
  {
    department_Id: 20,
    timekeeper_Name: "Test",
    office_Id: 1,
    position_Id: 1
  },
  {
    department_Id: 21,
    timekeeper_Name: "Tesd332t",
    office_Id: 1,
    position_Id: 1
  },
  {
    department_Id: 20,
    timekeeper_Name: "Tesct123",
    office_Id: 2,
    position_Id: 2
  },
  {
    department_Id: 21,
    timekeeper_Name: "Tesat1ffg23",
    office_Id: 2,
    position_Id: 2
  },
  {
    department_Id: 22,
    timekeeper_Name: "Tesvtda",
    office_Id: 2,
    position_Id: 1
  }
];
var filters = [{department_Id: 20}];
var filteredData = timekeepersList.filter(tk => {
  // change .every to .some if you want partial matches
  return filters.every(function (filter) {
    // change .every to .some if you want partial matches
    return Object.keys(filter).every(function (key) {
      return tk[key] === filter[key];
    });
  });
});

console.log(filteredData);