Filter array of objects based on another array of objects in javascript

前端 未结 2 624
小蘑菇
小蘑菇 2021-01-20 16:02

I have an array like this

arr1 =
[
   {A: \'red\', B: \'blue\'},
   {Q: \'green\', R: \'blue\'},
   {B: \'green\', M: \'red\'},
   {Q: \'white\', R: \'blue\         


        
相关标签:
2条回答
  • 2021-01-20 16:40

    You can do this with fiter(), some() and every()

    var arr1 = [{"A":"red","B":"blue"},{"Q":"green","R":"blue"},{"B":"green","M":"red"},{"Q":"white","R":"blue"}]
    var filter = [{"A":"val","B":"someval"},{"B":"anothervalue","M":"value"}]
    
    var result = arr1.filter(function(e) {
      return filter.some(function(a) {
        var keyE = Object.keys(e);
        var keyA = Object.keys(a);
    
        return keyE.length == keyA.length && keyE.every(function(k) {
          return keyA.includes(k)
        })
      })
    })
    
    console.log(result)

    0 讨论(0)
  • 2021-01-20 16:41

    You could use a Set for the property names and filter the array.

    var array = [{ A: 'red', B: 'blue' }, { Q: 'green', R: 'blue' }, { B: 'green', M: 'red' }, { Q: 'white', R: 'blue' }],
        filter = [{ A: 'val', B: 'someval' }, { B: 'anothervalue', M: 'value' }],
        getKey = o => Object.keys(o).sort().join('|'),
        result = array.filter((s => o => s.has(getKey(o)))(new Set(filter.map(getKey))));
       
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
提交回复
热议问题