亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據來自另一個對象數組的多個值過濾對象數組

根據來自另一個對象數組的多個值過濾對象數組

qq_花開花謝_0 2022-07-15 09:33:48
我有一個對象數組,c = [  {     name: 'abc',     category: 'cat1',     profitc: 'profit1',     costc: 'cost1'  },  {     name: 'xyz',     category: '',     profitc: 'profit1',     costc: ''  },  {     name: 'pqr',     category: 'cat1',     profitc: 'profit1',     costc: ''  }]現在我想根據另一個對象數組過濾數組,第二個對象數組是,arr = [ {   type:'profitc'   value: 'profit1', }, {   type:'category'   value: 'cat1', }]現在 arr 顯示在帶有多個選擇選項的下拉列表中,并且對象中的鍵值的值顯示給用戶,即利潤 1、cat1 等。因此,如果用戶選擇profit1and cat1,那么我需要過濾數組c,這樣,輸出看起來像這樣。c = [  {     name: 'abc',     category: 'cat1',     profitc: 'profit1',     costc: 'cost1'  },  {     name: 'pqr',     category: 'cat1',     profitc: 'profit1',     costc: ''  }]我試著這樣做。let result = c.filter(e => {  let istruecat = true//arr is chosen value from user.  arr.forEach(element => {    istruecat = e[element.type] == element.value;  })  return istruecat;})但是當我這樣做時,我會從c數組中獲取所有對象。我在這里做錯了什么?有沒有辦法使用 lodash.
查看完整描述

4 回答

?
DIEA

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; }


查看完整回答
反對 回復 2022-07-15
?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

-您istruecat僅根據arr. 您應該使用 reduce 來累積值:


let result = c.filter(e => arr.reduce((acc, element) => acc && e[element.type] === element.value, true))


查看完整回答
反對 回復 2022-07-15
?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

這是c通過過濾器數組根據給定值減少列表的實現arr。請注意,輸出是基于 中的初始內容的新列表c。


result = arr.reduce((acc, curr) => {

    acc = acc.filter(item => {

        return item[curr.type] === curr.value;

    });


    return acc;

}, c);


查看完整回答
反對 回復 2022-07-15
?
FFIVE

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);


查看完整回答
反對 回復 2022-07-15
  • 4 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號