MT3
MT3

Reputation: 1065

How to loop through multidimensional array and map field to key

I have an object structured like this:

[
  {
    "ID": 34,
    "parent": 0,
    "title": "Level 1 A",
    "children": []
  },
  {
    "ID": 35,
    "parent": 0,
    "title": "Level 1 B",
    "children": [
      {
        "ID": 36,
        "parent": 35,
        "title": "Level 2 A",
        "children": [
          {
            "ID": 37,
            "parent": 36,
            "title": "Level 3 A",
            "children": []
          },
          {
            "ID": 38,
            "parent": 36,
            "title": "Level 3 B",
            "children": []
          }
        ]
      }
    ]
  }
]

and I'm trying to loop through it and make the "title" the key so I end up with this:

[
  {
    "Level 1 A": {
      "ID": 34,
      "parent": 0,
      "title": "Level 1 A",
      "children": []
    }
  },
  {
    "Level 1 B": {
      "ID": 35,
      "parent": 0,
      "title": "Level 1 B",
      "children": [
        {
          "Level 2 A": {
            "ID": 36,
            "parent": 35,
            "title": "Level 2 A",
            "children": [
              {
                "Level 3 A": {
                  "ID": 37,
                  "parent": 36,
                  "title": "Level 3 A",
                  "children": []
                }

              },
              {
                "Level 3 B": {
                  "ID": 38,
                  "parent": 36,
                  "title": "Level 3 B",
                  "children": []
                }
              }
            ]
          }

        }
      ]
    }
  }
]

I tried something like this, but it doesn't go through the children arrays so only the Level 1 elements get updated:

    for (var i = 0, l = response.length; i < l; i++) {
        map[response[i].title] = response[i];
    }

I believe I need to use some recursion, but I'm having trouble figuring out how to get this done with Javascript. Thanks in advance for any suggestions.

Upvotes: 1

Views: 599

Answers (2)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

You need to update your code to following

function updateArray(arr) {
    var updatedResponse = [];
    for (var i = 0, l = arr.length; i < l; i++) {
        var obj = {};
        if(arr[i].children !== undefined) {
            arr[i].children = updateArray(arr[i].children);
        }
        obj[arr[i].title] = arr[i];
        updatedResponse.push(obj);
  }
  return updatedResponse;
}

var updatedArray = updateArray(response);

For reference - http://plnkr.co/edit/bXloL9VHxuxzOlZkHBTe?p=preview

Upvotes: 1

Constuntine
Constuntine

Reputation: 508

To loop through multidimensional arrays, you need multiple nested for loops.

for(var i = 0, l = response.length; i < l; i ++){
    for(var j = 0, k = response.length; j < k; j ++){
        //Do some code here
    }
}

A general rule is for every dimension in the array, you need another loop.

Upvotes: 0

Related Questions