簡體   English   中英

如何使用 javascript 從與 id 匹配的對象的遞歸數組中找到 object 並做出反應?

[英]How to find an object from recursive array of objects that is matching with the id using javascript and react?

我有如下數據,

const items = [
    {
        id: '1',
        name: 'item1',
        subItems: [{
            id: '1',
            name: 'subitem-1',
        }],
    },
    {
        id: '2',
        name: 'item2',
        subItems: [{
            id: '2',
            name: 'subitem-1',
        }],
    }
]

現在我想找到與 id 2 匹配的子項。所以從上面的數據預期 output 是

{
    id: '2',
    name: 'subitem-1',
}

我嘗試過類似下面的方法,

const subItem = Items.find(
    (item: any) =>
        item.subItems &&
            item.subItems.some(
                (subItem: any) => subItem.id === '2'
            )
);

但這將返回包含 id = '2' 的 subItem 的項目。

我怎樣才能修復上面的代碼,以便我得到 SubItem 而不是項目?

有人可以幫我解決這個問題。 謝謝。

您可以使用以下內容,它將僅搜索並返回找到的內部 object。

 const items = [ { id: "1", name: "item1", subItems: [ { id: "1", name: "subitem-1" } ] }, { id: "2", name: "item2", subItems: [ { id: "2", name: "subitem-1" } ] } ]; function innerFind(array, key, value) { for (const obj of array) { const item = obj.subItems.find((el) => el[key] === value); if (item;= null) return item. } } console,log(innerFind(items, 'id'; '2'));

你傳入你的 items 數組,你想要搜索的鍵 ('id'),然后是你想要搜索的值 ('2')。 這個 function 將返回它找到的第一個匹配的子項。

暫無
暫無

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

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