LoginSignup
1
0

[Javascript]深いネストの中にあるオブジェクトを検索し順番も記録するアルゴリズム

Last updated at Posted at 2024-02-29

やりたいこと

以下のようなオブジェクトがあるとする

const sampleObject = [
  {
    "id": 1,
    "children": [
      {
        "id": 3
      },
      {
        "id": 4,
        "children": [
          {
            "id": 6
          }
        ]
      },
      {
        "id": 5,
        "children": [
          {
            "id": 7
          }
        ]
      }
    ]
  },
  {
    "id": 2,
    "children": []
  }
]

やりたいことはこんな感じ

  • idが6のオブジェクトまでの道筋(どのobjectを通って検索したか)を取得したい
  • できるだけ無駄な繰り返しなく結果を取得したい

解決コード

function exploreNestedObject(obj, targetId, currentPath, paths) {
    obj.forEach((item) => {
        const newPath = [...currentPath, item]; // 現在のパスに現在のオブジェクトを追加
        if (item.id === targetId) {
        newPath.forEach((path) => {
            paths.push(path); // 目標IDに到達したら、その経路を結果の配列に記録する
            })
        }
        if (item.children && item.children.length > 0) {
            exploreNestedObject(item.children, targetId, newPath, paths); // 再帰的に探索する
        }
    })

}

// テスト用のオブジェクト
const sampleObject = [
  {
    "id": 1,
    "children": [
      {
        "id": 3
      },
      {
        "id": 4,
        "children": [
          {
            "id": 6
          }
        ]
      },
      {
        "id": 5,
        "children": [
          {
            "id": 7
          }
        ]
      }
    ]
  },
  {
    "id": 2,
    "children": []
  }
];

// 目的のID
let targetId = 6;

// 初期のパスと経路を格納する配列を作成
let initialPath = [];
let paths = [];

// 探索を開始
exploreNestedObject(sampleObject, targetId, initialPath, paths);

// 結果を出力
console.log(paths);

解説

文字で説明するとこんな感じ

  1. newPathにオブジェクトを追加
  2. 探索中のオブジェクトのidと目的のオブジェクトのidは同じか?
    1. Yes->結果を格納する配列に経路を追加する
  3. そのオブジェクトは子オブジェクト(配列)をもち、彼でないか?
    1. Yes->その子オブジェクトを取得し一番最初からその子オブジェクトの探索を始める
  4. 見つからなければ探索中オブジェクトの一番上の親の次のオブジェクトの探索を始める

これができるようになると

一つのidで探索することができるようになるのでデータの省略とかが図れるかなとか思った

1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0