从循环中的另一个数组中过滤掉对象

时间:2017-10-23 17:10:01

标签: javascript arrays

我有allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ] 个对象数组

fewItems = [
    { id: 2, name: 'item2' }
]

我希望它过滤掉而不包含我组件中另一个数组中包含的对象。

filteredItems

所以,filteredItems = [ { id: 1, name: 'item1' }, { id: 3, name: 'item3' } ] 应该是:

allItems

fewItems中的另一个对象添加到filteredItems时,它需要从@NgModule({ imports: [ CommonModule, HttpClientModule, ], declarations: [ ], exports: [ CommonModule, ], providers: [ ] }) export class SharedModule { static forRoot(): ModuleWithProviders { return { ngModule: SharedModule, providers: [ HttpClient, { provide: HTTP_INTERCEPTORS, useClass: JwtHttpInterceptor, multi: true } ] }; } } 消失。

我想在纯香草JS中做这个,没有特定的库。

提前致谢!

4 个答案:

答案 0 :(得分:1)

output+= current.getElement();
var allItems = [
    { id: 1, name: 'item1' },
    { id: 2, name: 'item2' },
    { id: 3, name: 'item3' }
];

var fewItems = [
    { id: 2, name: 'item2' }
];

var result3 = _(allItems) 
        .differenceBy(fewItems, 'id', 'name')
        .map(_.partial(_.pick, _, 'id', 'name'))
        .value();

console.log(result3);

 

修改

没有Lodash

<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

答案 1 :(得分:1)

var allItems = [
     { id: 1, name: 'item1' },
        { id: 2, name: 'item2' },
        { id: 3, name: 'item3' }
    ];
    
    var fewItems = [
        { id: 2, name: 'item2' }
    ];
    
    var keys = Object.keys( fewItems[0] ) 
    
    var result = allItems.filter( 
      function(item){ 
        for( var k = fewItems.length-1; k>=0; --k){ 
          var dontWant = fewItems[k]; 
          var i=keys.length-1; 
          for( ; i>=0; --i ){ 
            if( dontWant[keys[i]] != item[keys[i]]){  break; } 
          } 
          if( i == -1){ return false;} 
        } 
        return true; 
      }
    );

    console.log(result)

答案 2 :(得分:1)

纯JS解决方案

&#13;
&#13;
var allItems = [
  { id: 1, name: 'item1' },
  { id: 2, name: 'item2' },
  { id: 3, name: 'item3' }
];

var fewItems = [
  { id: 2, name: 'item2' }
];

var result3 = allItems
  .filter(item => {
    for(let restrictedItem of fewItems) {
      if (JSON.stringify(restrictedItem) === JSON.stringify(item)) {
        return false;
      }
    }
    return true;
  })

console.log(result3);
&#13;
&#13;
&#13;

答案 3 :(得分:1)

filteredItems =  this.allItems.filter(x => {
    return !this.fewItems.some(y => JSON.stringify(y) == JSON.stringify(x))
});