簡體   English   中英

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

[英]Filter array of objects based on multiple values from another array of objects

我有一個對象數組,

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',
 }
]

Now the arr is shown in dropdown with multiple select option and the value of key value in the object is shown to the user ie profit1, cat1, etc. So if a user selects profit1 and cat1 , then I need to filter the array c such也就是說,output 看起來像這樣。

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.

-您僅根據arr中的最后一個條目計算istruecat 您應該使用 reduce 來累積值:

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

您可以通過使用數據對象檢查所有給定的鍵/值對來過濾數組。

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

這是基於過濾器數組arr的給定值減少列表c的實現。 請注意, output 是基於c中的初始內容的新列表。

result = arr.reduce((acc, curr) => {
    acc = acc.filter(item => {
        return item[curr.type] === curr.value;
    });

    return acc;
}, c);

或者一個遞歸和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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM