idやname、childといった要素を持つ連想配列において、nameが一番長いオブジェクトを取得して値を返却すということを実現したいと思っています。
まず想定している連想配列が下記のような形です。
TypeScript
1interface Tree { 2 id: string 3 name: string 4 child?: Tree[] 5} 6const treeArray: Tree[] = [ 7 { 8 id: "test", name: "test1", child: [ 9 { id: "Test#2", name: "@2ndtest" }, 10 { 11 id: "test#2", name: "2ndtest", child: [ 12 { id: "Test#2#3", name: "@3rdtestTestTest" }, 13 ] 14 } 15 ] 16 }, 17 { id: "testtest", name: "testtest2" } 18]
treeArayという配列の中から、nameが一番長いものを取り出し、
そのオブジェクトを取り出したいと思っています。
そのため、想定しているアウトプットとしては{ id: "Test#2#3", name: "@3rdtestTestTest" }
を考えています。
そこで、forEachを使用して、下記のようなコードを作成しました。
TypeScript
1const getLongestNameObjectInTreeArray = (value: Tree[]) => { 2 let getObj: Tree = { id: "", name: "" } 3 let longestName = 0 4 value.forEach((v) => { 5 let nameLength = v.name.length 6 if (<any>nameLength > longestName) { 7 longestName = <any>nameLength 8 getObj = { id: v.id, name: v.name } 9 } 10 }) 11 return getObj 12} 13console.log(getLongestNameObjectInTreeArray(treeArray))
しかし、このコードだとアウトプットは、{ id: 'testtest', name: 'testtest2' }
となってしまいます。
forEachがネストとなったchild配列の中をループできていないため、
このような結果になったいうことは分かるのですが、
どうしたら、ネストとなったchildの部分もループを回し
欲しい結果を得ることができるのか、困っております。
どなたかお詳しい方、アドバイスいただけますと幸いです。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/04/21 00:35