1

I hope you can help me. How to convert this flat JavaScript array, from:

[
    {"state":"First State","district":"First District","local_district_id":1,"zone_id":117,"center_id":"A","center_name":"Voting Center First"},
    {"state":"First State","district":"First District","local_district_id":2,"zone_id":117,"center_id":"B","center_name":"Voting Center Second"},
    {"state":"First State","district":"First District","local_district_id":6,"zone_id":117,"center_id":"C","center_name":"Voting Center Third"},
]

into a nested array, like so:

[{
    "state": "First State",
    "children": [{
        "district_name": "First District",
        "children": [{
            "local_district_id": 1,
            "zone_id": 117,
            "center_id": "A",
            "center_name": "Voting Center Name First",
        }, {
            "local_district_id": 2,
            "zone_id": 117,
            "center_id": "B",
            "center_name": "Voting Center Name Second",
        }, {
            "local_district_id": 6,
            "zone_id": 117,
            "center_id": "C",
            "center_name": "Voting Center Name Third",
        }]
    }]
}]
4
  • 3
    I sense there will be lots of looping involved. Commented Nov 10, 2014 at 23:51
  • 1
    A couple of underscore groupBy's ought to do the trick. Would you consider that? Commented Nov 11, 2014 at 1:34
  • Yes, I am considering anything that works. I've tried so many loops, but it seems that my JS loop skills aren't anywhere near solving this sort of problem. Commented Nov 12, 2014 at 16:32
  • Even though Jonathan's answer did the trick, I would appreciate seeing an underscore approach to this as I tried it yesterday and couldn't figure out how to use groupBy. Commented Nov 12, 2014 at 17:31

2 Answers 2

2

You could do something like this to get this working with a single loop. Not the prettiest function but it gets the job done without a lot of extra overhead.

<script>
var original = [
    {"state":"First State","district":"First District","local_district_id":1,"zone_id":117,"center_id":"A","center_name":"Voting Center First"},
    {"state":"Second State","district":"First District","local_district_id":2,"zone_id":117,"center_id":"B","center_name":"Voting Center Second"},
    {"state":"First State","district":"First District","local_district_id":6,"zone_id":117,"center_id":"C","center_name":"Voting Center Third"},
];

var statesUsed = {};
var districtsUsed = {};
var newArray = [];
var stateIndex = 0;
var districtIndex = 0;

for (var i=0,l=original.length;i<l;i++) {
    var state = original[i].state;
    var district = original[i].district;
    var local_district_id = original[i].local_district_id;
    var zone_id = original[i].zone_id;
    var center_id = original[i].center_id;
    var center_name = original[i].center_name;

    if (statesUsed[state] == undefined) {
        statesUsed[state] = stateIndex;
        stateIndex++;
        newArray.push({state : state, children : []});
    }

    districtsUsed[state] = (districtsUsed[state] == undefined) ? {} : districtsUsed[state];

    if (districtsUsed[state][district] == undefined) {
        newArray[statesUsed[state]].children.push({district_name : district, children : []});
        districtsUsed[state][district] = newArray[statesUsed[state]].children.length - 1;
    }

    newArray[statesUsed[state]].children[districtsUsed[state][district]].children.push({
          local_district_id : local_district_id,
          zone_id : zone_id,
          center_id : center_id,
          center_name : center_name
    });


}
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

EDIT: Forgot the obvious...but:

  JSON = [
    {"state":"First State","district":"First District","local_district_id":1,"zone_id":117,"center_id":"A","center_name":"Voting Center First"},
    {"state":"First State","district":"First District","local_district_id":2,"zone_id":117,"center_id":"B","center_name":"Voting Center Second"},
    {"state":"First State","district":"First District","local_district_id":6,"zone_id":117,"center_id":"C","center_name":"Voting Center Third"},
]

messy, but... something like this

newObj = {};

for (var i in JSON) {

    if (!newObj.length) {
        newObj.push({'state': JSON[i]['state']})
        delete([JSON[i]['state'])
        newObj[0]['children'] = [JSON[i]]
        continue
    }
    for (var j in newObj) {
        if (newObj[j]['state'] = JSON[i]['state']) {
            delete([JSON[i]['state'])
            newObj[j]['children'].push(JSON[i])
         } else {

        newObj.push({'state': JSON[i]['state']})
        delete([JSON[i]['state'])
        newObj[newObj.length-1]['children'] = [JSON[i]]
         }

    }

}

2 Comments

thanks for the edit! I couldn't for the life of me figure out how to fix that :P
No problem, just highlight all your code and press the {} icon at the top

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.