根据另一个对象数组过滤一个对象数组(有序)

问题描述 投票:0回答:1

这是我的数据:

arrayA= [{"studentID":1,"Type":"A"},{"studentID":2,"Type":"B"},{"studentID":3,"Type":"C"},{"studentID":4,"Type":"A"}]
filteredArrayOrderlyOn = [{"studentID":1},{"Type":"A"}] (depending on the order the user selects the filters)

Output should be 
arrayA = [{"studentID":1,"Type":"A"}]

或者如果filteredArrayOrderlyOn数组发生变化,因为用户可以控制此选择。

filteredArrayOrderlyOn  = [{"Type":"B"},{"studentID":1}] then output should be nothing []

所以我想以正确的顺序过滤ArrayA,这意味着在filteredArrayOrderly中,首先过滤器应该是studentID=1,然后是A。

我一直在尝试但没有运气


newArray = arrayA.filter(function (item) {
    return Object.keys(elem) === Object.keys(item);
  });
})

或使用lodash

 newArray = _.filter(arrayA, function (elem) {
  //     return elem.Type=== filteredArrayOrderlyOn.Type ||  elem.studentID=== filteredArrayOrderlyOn.studentID
  //   });

但重复次数过多 谢谢大家

javascript arrays vue.js lodash
1个回答
0
投票

试试这个

let arrayA = [
  { "studentID": 1, "Type": "A" },
  { "studentID": 2, "Type": "B" },
  { "studentID": 3, "Type": "C" },
  { "studentID": 4, "Type": "A" }
];

let filteredArrayOrderlyOn = [
  { "studentID": 1 },
  { "Type": "A" }
];

let filteredArray = arrayA;

filteredArrayOrderlyOn.forEach(filter => {
  const key = Object.keys(filter)[0];
  const value = filter[key];
  filteredArray = filteredArray.filter(item => item[key] === value);
});

console.log(filteredArray);
© www.soinside.com 2019 - 2024. All rights reserved.