1

I'm trying to build a dynamic tree structure in html. I'm getting result from database in nested json format.

JSON DATA

I'm not able to read the json data properly. It is in the format

[ { keys_1 : { keys_2 : [ array ] } } ]

In the tree structre, key_1 are the parents, key_2 are childern, array items are grand-childern.

How to access this json data so that i can read the parent keys, associated children and then grand children.

I tried this way but couldn't do that:

for (var i = 0; i < response.length; i++) {
    var level_1 = (JSON.stringify((Object.keys(response[i]))[0])).replace(/"/g, "");
    for (var j = 0; j < response[i].length; j++) {
        console.log("yes");
    }
}

Even, i'm not able to figure out how to enter the nested json with different key values. - All keys are different. - Keys may/may not have children, same with the children also.

How to read the json data in that way so that first it should read one parent children then grandchildren?

1
  • How about scaling that data sample down to a much smaller sampling....just enough to create a minimal reproducible example. Also provide a sample of expected results Commented Jan 11, 2018 at 19:04

1 Answer 1

2

You could use a nested approach, because you have the following structure:

  • array: iterate,
  • object: take keys for iterating,
  • object: take keys for iterating,
  • array: iterate.

var data = [{ 1000: { 110: ["1000110008", "1000110005", "1000110004", "1000110003", "1000110001", "1000110009"], 100: ["1000100001", "1000100002", "1000100019", "1000100018", "1000100017", "1000100015", "1000100014", "1000100013", "1000100003", "1000100004", "1000100006", "1000100007", "1000100008", "1000100009", "1000100011"] } }, { 1020: { 102: ["1020102001"] } }];

data.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        Object.keys(o[k]).forEach(function (l) {
            o[k][l].forEach(function (v) {
                console.log(k, l, v);
            });
        });
    });
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.