我有以下数据:
const myArr = [{
id: 0,
company: "microsoft",
location: "berlin"
}, {
id: 1,
company: "google",
location: "london"
}, {
id: 2,
company: "twitter",
location: "berlin"
}];
let myObj = {
company: ["google", "twitter"],
location: ["london"]
}
并考虑到myObj.company条目正在更改(无关紧要),我试图创建一个过滤结果并仅返回满足位置和公司条件的对象的函数.
在上面的示例中,我们需要返回的是:
{
id: 1,
company: "google",
location: "london"
}
如果myObj是
let myObj = {
company: ["google", "twitter"],
location: []
}
那么返回的结果应该是
{
id: 1,
company: "google",
location: "london"
},
{
id: 2,
company: "twitter",
location: "berlin"
}
解决方法:
使用Array.prototype.filter,Array.prototype.every和Object.keys来获得所需的结果,如下所示:(请注意obj可以具有任意数量的键,这种方式很灵活)
const myArr = [{
id: 0,
company: "microsoft",
location: "berlin"
}, {
id: 1,
company: "google",
location: "london"
}, {
id: 2,
company: "twitter",
location: "berlin"
}];
let myObj = {
company: ["google", "twitter"],
location: ["london"]
}
function find(arr, obj) {
// get only the keys from obj that their corresponding array is not empty
var keys = Object.keys(obj).filter(k => obj[k].length !== 0);
// return a filtered array of objects that ...
return arr.filter(o => {
// ... met the creteria (for every key k in obj, the current object o must have its value of the key k includded in the array obj[k])
return keys.every(k => {
return obj[k].indexOf(o[k]) != -1;
});
});
}
console.log(find(myArr, myObj));