簡體   English   中英

針對另一個對象過濾對象數組

[英]Filtering an array of objects against another object

我有一些對象,需要按特定條件過濾。 我在弄清楚for循環中if語句的邏輯時遇到麻煩。 我隨附了一個代碼段,您可以在其中調整條件並查看我要解決的問題。 任何想法或建議都將不勝感激,謝謝!

根據以下條件,我只能在foundItems數組中得到1個找到的項目:

const criteria = {
    title: 'title',
    character: 'Z',
    type: ['second'],
};

這應該(並且確實)返回所有三個項目:

const criteria = {
    title: 'title',
    character: '',
    type: [],
};

這應該返回前兩個項目:

const criteria = {
    title: 'title',
    character: 'R',
    type: [],
};

這應該返回所有三個項目:

const criteria = {
    title: '',
    character: '',
    type: ['first','second'],
};

 const data = [ { label: { title: 'A title', }, character: 'R', type: 'first', }, { label: { title: 'Another title', }, character: 'R', type: 'second', }, { label: { title: 'A more interesting title', }, character: 'Z', type: 'second', }, ]; const criteria = { title: 'title', character: 'Z', type: ['second'], }; const createRegEx = (value) => { const regex = value .split(' ') .filter(Boolean) .map((word) => `(?=^.*${word})`) .join(''); return new RegExp(regex, 'i'); } const foundItems = []; for (let i = 0; i < data.length; i++) { const item = data[i]; if ( item.label.title.match(createRegEx(criteria.title)) || item.character === criteria.character || criteria.type.includes(item.type) ) { foundItems[foundItems.length] = item; } } console.log(foundItems); 

這表明我相信是您的意圖。 請讓我知道是否需要更正。 我有些自由地簡化了代碼,但是我不知道是否需要使用正則表達式。

filter方法對每個數據元素應用一個過濾器,如果該過濾器的標准是匹配一個短語,則匹配,返回true將保留該元素。

三元運算符是確定輸入是否與匹配相關的必要條件。 如果為空,則不會根據該條件過濾數據。

最后一點是我相信您所缺少的:

 const data = [ { label: { title: 'A title', }, character: 'R', type: 'first', }, { label: { title: 'Another title', }, character: 'R', type: 'second', }, { label: { title: 'A more interesting title', }, character: 'Z', type: 'second', }, ]; const criteria = { title: '', character: 'R', type: ['second'], }; const foundItems = data.filter(item=>{ let t = (criteria.title.length) ? item.label.title.includes(criteria.title) : true; let c = (criteria.character.length) ? item.character === criteria.character : true; let p = (criteria.type.length) ? criteria.type.includes(item.type) : true; return t && c && p; }); console.log(foundItems); 

暫無
暫無

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

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