TheUser TheUser - 6 months ago 7
JSON Question

Multidimensional json to single ones

I've just need to switch multidimensional json to single to provide it for js-plugin for creating tables.

Here's an example of response:

[
{
"services": [],
"id": 1,
},
{
"services": [
{
"status": {
...
},
"name": "NAME"
},
{
"status": {
...
},
"name": "NAME 2"
}
],
"id": 2
}
]


What I looking for:

[
{
"services": [],
"id": 1,
},
{
"service": {name: 'NAME', status: '' ...},
"id": 2,
},
{
"service": {name: 'NAME 2', status: '' ...},
"id": 2,
}
...
]


The idea is to create new array of entries with same id's and only one service.

Here's a loops:

function parseData(json) {
var newArray = [];
for (i = 0; i < json.length; i++){
var item = json[i];
if (item.services.length > 0) {
for (j = 0; j < item.services.length; j++){

item['service'] = item.services[j];
newArray.push(item);
}
}
else {
newArray.push(item);
}
}
return newArray;
}


Finally, instead of two objects with different single service entry I get two object with same 'service' entries. What's wrong with this loops?

Here's JSfiddle: https://jsfiddle.net/ghea33x1/

Thank you.

Answer

You are mutating the object in this line

item['service'] = json[i].services[j];

A fast way would be a loop with Array#forEach without mutating the origin.

var data = [{ "services": [], "id": 1, }, { "services": [{ "status": {}, "name": "NAME" }, { "status": {}, "name": "NAME 2" }], "id": 2 }],
    grouped = [];

data.forEach(function (a) {
    if (!a.services.length) {
        grouped.push(a);
        return;
    }
    a.services.forEach(function (b) {
        grouped.push({ services: b, id: a.id });
    });
});

console.log(grouped);