const usersLanguageData = {
transactionId: 6847655349501841000,
count: 5,
providerList: [
{
code:['US'],
weekendOfficeHours: false
},
{
code:['US','IND'],
weekendOfficeHours: true
},
{
code:['US','IND','AUS'],
weekendOfficeHours: false
},
{
code:[],
weekendOfficeHours: false
},
{
weekendOfficeHours: true
}
]
};
let filterKeyName1 = ["code"];
let filterValue1 = ['IND','US'];
//let filterValue2 = ['US'];
let filteredProviderData = usersLanguageData.providerList.filter(function(e) {
return filterKeyName1.every(function(a) {
console.log(e[a])
return filterValue1.includes(e[a]);
});
});
console.log(filteredProviderData);
此处的代码段将usersLanguageData显示为对象形式。 在这里我想用关键字说来过滤值,例如在这里 filterKeyName1 = ['code']和filterValue1 = ['IND','US'],它将把第二个和第三个对象显示到usersLanguageData对象中。 同样,在注释行中也有filterValue2,它将显示usersLanguageData中的1st,2nd和3rd对象。
答案 0 :(得分:1)
您应该在函数内再次使用every()
。并且还可以在使用e[a]
之前先检查every()
是否存在,因为您的商品之一没有code
键
const usersLanguageData = { transactionId: 6847655349501841000, count: 5, providerList: [ { code:['US'], weekendOfficeHours: false }, { code:['US','IND'], weekendOfficeHours: true }, { code:['US','IND','AUS'], weekendOfficeHours: false }, { code:[], weekendOfficeHours: false }, { weekendOfficeHours: true } ] };
let filterKeyName1 = ["code"];
let filterValue1 = ['IND','US'];
//let filterValue2 = ['US'];
let filteredProviderData = usersLanguageData.providerList.filter(function(e) {
return filterKeyName1.every(function(a) {
console.log(e[a])
return e[a] && filterValue1.every(x => e[a].includes(x));
});
});
console.log(filteredProviderData);
答案 1 :(得分:1)
您可以使用值进行过滤,并针对对象的属性或空数组进行过滤。
const usersLanguageData = { transactionId: 6847655349501841000, count: 5, providerList: [{ code: ['US'], weekendOfficeHours: false }, { code: ['US','IND'], weekendOfficeHours: true }, { code: ['US','IND','AUS'], weekendOfficeHours: false }, { code: [], weekendOfficeHours: false }, { weekendOfficeHours: true }] };
let key = "code";
let values = ['IND','US'];
let result = usersLanguageData.providerList
.filter(o => values.every(v => (o[key] || []).includes(v)));
console.log(result);