簡體   English   中英

基於單獨的對象鍵、值過濾對象數組

[英]filter array of objects based on separate object keys, values

我有以下人員:

  const FIRST_ARRAY = [
    {
      name: 'Simon',
      age: 32,
      occupation: 'Student'
    },
    {
      name: 'Vera',
      age: 22,
      occupation: 'Developer'
    }
  ];

我想過濾數組以基於“過濾器”對象生成一個單獨的數組。

例如,如果我的過濾器是:

  const FILTERS = {
    age: 32,
    name: 'John',
    occupation: ''
  };

新數組應該是空的,因為數組中沒有人具有 32 和 John 的組合。 但是,如果我的過濾器是:

 const FILTERS = {
    age: 32,
    name: 'Simon',
    occupation: ''
  }

返回的新人員數組將是:

 const NEW_ARRAY = [
    {
      name: 'Simon',
      age: 32,
      occupation: 'Student'
    }
  ];

如何通過迭代“過濾器”對象值來過濾人員數組? 請記住,過濾器的鍵和值會一直動態變化。

您可以按如下方式過濾:

 const FIRST_ARRAY = [ { name: 'Simon', age: 32, occupation: 'Student' }, { name: 'Vera', age: 22, occupation: 'Developer' } ]; const FILTERS = { name: 'Simon', age: 32, occupation: '' }; const filtered = FIRST_ARRAY.filter(person => Object.entries(FILTERS) .every(([key, val]) => val !== '' ? person[key] === val : true)); console.log(filtered);

您可以使用函數filter和函數every來檢查每個鍵值是否等於FILTERS值。

假設在 FILTERS 中的值是空的,然后跳過它

 const FIRST_ARRAY = [{name: 'Simon',age: 32,occupation: 'Student'},{name: 'Vera',age: 22,occupation: 'Developer'}], FILTERS = {age: 32,name: 'Simon',occupation: ''}, keys = Object.keys(FILTERS), result = FIRST_ARRAY.filter(o => keys.every(k => FILTERS[k] === '' || FILTERS[k] === o[k])); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }
 const FILTERS = { age: 32, name: 'John', occupation: '' };

您可以嘗試以下操作:

 function compare(item, filter) { for (var property in filter) { if (filter.hasOwnProperty(property)) { let value = filter[property]; return item.hasOwnProperty(property) && item[property] != '' && value == item[property]; } } } const DATA = [ { name: 'Simon', age: 32, occupation: 'Student' }, { name: 'Vera', age: 22, occupation: 'Developer' } ]; const filter = { age: 32, name: 'Simon', occupation: '' }; let result = DATA.filter(function(item) { return compare(item, filter); }) console.log(result);

暫無
暫無

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

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