@meto3ki6789 (貴大 石川)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ネストされたobjectをflatにしたい

解決したいこと

ネストされたobjectをflatにしたい

該当するソースコード

const hoge = [
{name:"1", value:"A",child:[{name:"3", value;"C"}]},
{name:"2", value:"B"}
]

//このような形にしたい
[
{name:"1", value:"A"},
{name:"2", value:"B"},
{name:"3", value;"C"}
]

//flatMapではundefinedにいなってしまう
hoge.flatMap(a => a.child)
[
{name:"1", value:"A"},
{name:"2", value:"B"},
undefined
]

自分で試したこと

hoge.flat()なども試しましたが、うまくいかずどのような方法があるでしょうか?

0 likes

3Answer

childの配列要素内にもまたchildが存在する可能性もありますか?
outputの形はある程度明確になっているので、inputの要件を明確にするといろんなパターンの回答がもらえそうな気がしました。

1Like

Comments

  1. @meto3ki6789

    Questioner

    回答ありがとうございます。
    childの配列要素内にもまたchildが存在する事はありません。

こんな感じでどうでしょうか?flatMapの中が少し汚い気がしますが、愚直にやるならまずはこんなところかなと思います。
一応、sortもつけましたが、不要なら外してもらって大丈夫です。

const targetArr = [
  { name: '1', value: 'A', child: [{ name: '3', value: 'C' }] },
  { name: '2', value: 'B' },
];

const result = targetArr
  .flatMap((obj) => {
    if (!('child' in obj)) {
      return obj;
    }
    return [{ name: obj.name, value: obj.value }, ...obj.child];
  })
  .sort((a, b) => a.name - b.name);
console.log(result);
1Like

Comments

  1. @meto3ki6789

    Questioner

    想定した並列のデータになり、大感動しています。
    自分ではたどり着けませんでした。
    本当にありがとうございます!
hoge.reduce((memo, record) => {
  const {child: children, ...parent} = record
  memo.push(parent)

  if(children){
    children.forEach((child) => {
      memo.push(child)
    })
  }

  return memo
}, [])
0Like

Your answer might help someone💌