Dominik Zinser Dominik Zinser - 23 days ago 11
Javascript Question

Struggeling with re-organisation of Json data structure

I m struggeling for so long now, now i got to look for some help of you guys.
I am trying to convert this json:

[
[
{
"id": 1,
"ac": 1
},
{
"id": 2,
"ac": 1
},
{
"id": 3,
"ac": 1
}
],
[
{
"id": 1,
"ac": 1
},
{
"id": 2,
"ac": 1
},
{
"id": 3,
"ac": 0
}
],
[
{
"id": 1,
"ac": 1
},
{
"id": 2,
"ac": 1
},
{
"id": 3,
"ac": 0
}
],
[
{
"id": 1,
"ac": 1
},
{
"id": 2,
"ac": 0
},
{
"id": 3,
"ac": 0
}
],
[
{
"id": 1,
"ac": 1
},
{
"id": 2,
"ac": 0
},
{
"id": 3,
"ac": 0
}
],
[
{
"id": 1,
"ac": 1
},
{
"id": 2,
"ac": 0
},
{
"id": 3,
"ac": 0
}
]
]


into that data structure:

[
[
{
"id": 1,
"ac": [1,1,1,1,1,1]
}
],
[
{
"id": 2,
"ac": [1,1,1,0,0,0]
}
],
[
{
"id": 3,
"ac": [1,0,0,0,0,0]
}
]
]


i am using javascript/ node to do so, but i cannot get it to work. can anyone help me to write a loop that can do so?? that would definitely save my day!
best regards to all of you

edit:
what i tried is, the following, but i guess it doesnt help a lot because it is still not the output that i need

var acc_array = [];
var a_id;
for(var y=0; y<data.length; y++) { //151
if(y<data.length-1){
a_id = data[y].a_id;
if(a_id == data[y].a_id) {
acc_array[y] = new Array();
acc_array[y].push(data[y].acc);
}
}
if(y==data.length-1){
acc_array[y] = new Array();
a_id = data[y].a_id;
if(a_id == data[y].a_id) {
acc_array[y].push(data[y].acc);
}
jsonfile.writeFile("a.json", acc_array, function (err) {
console.log(err);
});
}
}

Answer Source

You could take a nested loop and a hash table for collecting items with the same id.

var data = [[{ id: 1, ac: 1 }, { id: 2, ac: 1 }, { id: 3, ac: 1 }], [{ id: 1, ac: 1 }, { id: 2, ac: 1 }, { id: 3, ac: 0 }], [{ id: 1, ac: 1 }, { id: 2, ac: 1 }, { id: 3, ac: 0 }], [{ id: 1, ac: 1 }, { id: 2, ac: 0 }, { id: 3, ac: 0 }], [{ id: 1, ac: 1 }, { id: 2, ac: 0 }, { id: 3, ac: 0 }], [{ id: 1, ac: 1 }, { id: 2, ac: 0 }, { id: 3, ac: 0 }]],
    hash = Object.create(null),
    result = [];

data.forEach(function (a) {
    a.forEach(function (o) {
        hash[o.id] || result.push(hash[o.id] = { id: o.id, ac: [] });
        hash[o.id].ac.push(o.ac);
    });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }