4 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以通過(guò)使用數(shù)據(jù)對(duì)象檢查所有給定的鍵/值對(duì)來(lái)過(guò)濾數(shù)組。
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貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
-您istruecat
僅根據(jù)arr
. 您應(yīng)該使用 reduce 來(lái)累積值:
let result = c.filter(e => arr.reduce((acc, element) => acc && e[element.type] === element.value, true))

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

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
或者一個(gè)遞歸和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);
添加回答
舉報(bào)