簡體   English   中英

過濾嵌套數組時保留數組結構

[英]Retain array structure when filtering nested array

我的大腦被這種高級過濾器凍結了。 這個任務超出了我對filter的基本知識, map等。

在這里,我有一個帶有嵌套對象的數組:

const DATA = [
    {
        title: 'Spongebob',
        data: [
            { id: 1, name: 'Mr Crabs' },
            { id: 2, name: 'Sandy' }
        ]
    },
    {
        title: 'Dragon Balls Z',
        data: [
            { id: 1, name: 'GoKu' },
            { id: 2, name: 'Zamasu' }
        ]
    }
];

如果您使用過React Native (RN),您可能已經看到過這種風格。 這個問題不適用於 RN。 我需要對嵌套數組中的name屬性執行過濾器,當我得到匹配時,我必須將格式作為DATA變量返回。

const handleFiltering = (value) => {

    const _value = value.toLowerCase();

    const results = DATA.map(o => {
        return o.data.filter(o => o.name.toLowerCase().indexOf(_value) != -1)
    });

    console.log(results);
};

我對深度過濾的有限知識返回了data數組的基本過濾,但需要保留DATA的結構。 我期望的預期結果:


// I'm now querying for "ZAMASU"

const handleFiltering = (value='ZAMA') => {

    const _value = value.toLowerCase();

    const results = DATA.map(o => {
        return o.data.filter(o => o.name.toLowerCase().indexOf(_value) != -1)
    });

    // console.log(results) should now be
    // [
    //  {
    //      title: 'Dragon Balls Z',
    //     data: [
    //          { id: 2, name: 'Zamasu' }
    //      ]
    //  }
    // ];
};

我想到的是使用{...DATA, something-here }但我的大腦已經凍結,因為我需要取回 title 屬性。 請問這個怎么實現?

您可以使用數組的reduce方法。 首先找出數據數組中的 object,然后通過保留原始結構將其作為新條目添加到累加器數組中。

 const DATA = [ { title: 'Spongebob', data: [ { id: 1, name: 'Mr Crabs', where: 'tv' }, { id: 2, name: 'Sandy' } ] }, { title: 'Dragon Balls Z', data: [ { id: 1, name: 'GoKu' }, { id: 2, name: 'Zamasu' } ] } ]; let handleFiltering = (value='tv') => { return DATA.reduce((acc,d) => { let obj = d.data.find(a => a.name?.toLowerCase().includes(value.toLowerCase()) || a.where?.toLowerCase().includes(value.toLowerCase())); obj? acc.push({...d, data:[obj]}): null; return acc; }, []); } let result = handleFiltering(); console.log(result);

另一種解決方案是首先使用過濾器在通過參數傳遞的數據中僅查找包含名稱的對象,然后映射數據。

這是您調整后的過濾方法

const handleFiltering = (value) => {
  const _value = value.toLowerCase();

  const results = DATA.filter((obj) =>
    obj.data.some((character) => character.name.toLowerCase() === _value)
  ).map((obj) => ({
    title: obj.title,
    data: obj.data.filter(
      (character) => character.name.toLowerCase() === _value
    ),
  }));

  console.log(results);
};

暫無
暫無

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

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