簡體   English   中英

如何在 javascript 中循環遍歷對象的嵌套數組?

[英]How can loop through nested array of objects for this in javascript?

const array = [
{ 
id: "1",
children: [],
messages:[1, 'Text'],
entry: "Father",
},

{
id: "2",
entry: "Mother",
children: [
    {entry: "John Jr"},
    {entry: "Steven Jr"},
    {entry: "Tim Jr"},
    ],
messages:[2, 'Text'],
}, 

{
id: "3",
entry: "Son",
children: [
    {entry: "XXX Jr"},
    {entry: "Steven Jr"},
    {entry: "Tim Jr"}
    ],
 messages:[3, 'Text'],
 },
]

所以我想要的是,當我搜索“Tim”時。 我希望 output 成為

案例 1:當我搜索 Tim 時,我應該得到 id: 2 和 id: 3 的 object,因為 Tim 在兩個對象中都是匹配的條目。 所以我想以相同的順序返回整個 id:2 和 3 object。

{
id: "2",
entry: "Mother",
children: [
    {entry: "John Jr"},
    {entry: "Steven Jr"},
    {entry: "Tim Jr"},
    ],
messages:[2, 'Text'],
}, 

{
id: "3",
entry: "Son",
children: [
    {entry: "XXX Jr"},
    {entry: "Steven Jr"},
    {entry: "Tim Jr"}
    ],
 messages:[3, 'Text'],
 }

案例 2:當我搜索 John 時,我應該得到第二個 object

{
id: "2",
entry: "Mother",
children: [
    {entry: "John Jr"},
    ],
messages:[2, 'Text'],
}

案例 3:當我搜索 Steven 時,我應該得到 id:2 和 id:3 作為

id: "2",
entry: "Mother",
children: [
    {entry: "John Jr"},
    {entry: "Steven Jr"},
    ],
messages:[2, 'Text'],
}, 

{
id: "3",
entry: "Son",
children: [
    {entry: "XXX Jr"},
    {entry: "Steven Jr"},
    ],
 messages:[3, 'Text'],
 }

我用 .filter() 過濾頂層,但這不是檢查孩子。

array.filter((item) => item.entry.toUpperCase().includes(text.toUpperCase())); 

任何幫助將不勝感激,因為我在這里完全迷失了 forEach 。 提前致謝

 const data=[{id:"1",children:[],messages:[1,"Text"],entry:"Father"},{id:"2",entry:"Mother",children:[{entry:"John Jr"},{entry:"Steven Jr"},{entry:"Tim Jr"}],messages:[2,"Text"]},{id:"3",entry:"Son",children:[{entry:"XXX Jr"},{entry:"Steven Jr"},{entry:"Tim Jr"}],messages:[3,"Text"]}]; function finder(data, name) { // `filter` over the array return data.filter(obj => { // For each object check to see if // at least one of the entries in children // includes the name return obj.children.some(({ entry }) => { return entry.includes(name); }); }); } console.log(finder(data, 'Tim')); console.log(finder(data, 'John')); console.log(finder(data, 'Steven'));

您可以使用Array.FilterArray.some並將子數組與搜索entry object 的索引拼接

 const array = [{ id: "1", children: [], messages: [1, 'Text'], entry: "Father", }, { id: "2", entry: "Mother", children: [{ entry: "John Jr" }, { entry: "Steven Jr" }, { entry: "Tim Jr" }, ], messages: [2, 'Text'], }, { id: "3", entry: "Son", children: [{ entry: "XXX Jr" }, { entry: "Steven Jr" }, { entry: "Tim Jr" } ], messages: [3, 'Text'], }, ]; let searchText = 'John'; let result = array.filter(el => { let i; let found = el.children.some((e, j) => { i = j; return e.entry.toLowerCase().indexOf(searchText.toLowerCase()) >= 0; }); if (found) el.children = el.children.splice(0, i + 1); return found; }); console.log(result);

暫無
暫無

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

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