4 回答

TA貢獻1820條經驗 獲得超2個贊
您可以通過使用數據對象檢查所有給定的鍵/值對來過濾數組。
var data = [{ name: 'abc', category: 'cat1', profitc: 'profit1', costc: 'cost1' }, { name: 'xyz', category: '', profitc: 'profit1', costc: '' }, { name: 'pqr', category: 'cat1', profitc: 'profit1', costc: '' }],
filters = [{ type: 'profitc', value: 'profit1', }, { type: 'category', value: 'cat1' }],
result = data.filter(o => filters.every(({ type, value }) => o[type] === value));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

TA貢獻1847條經驗 獲得超11個贊
-您istruecat
僅根據arr
. 您應該使用 reduce 來累積值:
let result = c.filter(e => arr.reduce((acc, element) => acc && e[element.type] === element.value, true))

TA貢獻1876條經驗 獲得超6個贊
這是c通過過濾器數組根據給定值減少列表的實現arr。請注意,輸出是基于 中的初始內容的新列表c。
result = arr.reduce((acc, curr) => {
acc = acc.filter(item => {
return item[curr.type] === curr.value;
});
return acc;
}, c);

TA貢獻1797條經驗 獲得超6個贊
或者一個遞歸和imo可讀的解決方案:
function myFilter(c, [first, ...rest]) {
if (first) {
const {type, value} = first;
// Recursively call myFilter with one filter removed
return myFilter(c, rest)
.filter(x => x[type] === value);
} else {
// Nothing left to filter
return c;
}
}
myFilter(c, arr);
添加回答
舉報