Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Samiulcse/efe91036642dadd32701642c535b791b to your computer and use it in GitHub Desktop.

Select an option

Save Samiulcse/efe91036642dadd32701642c535b791b to your computer and use it in GitHub Desktop.
reorganize data for same type in javascript
var orig_json = {
"dishList": [{
"dishName": "bla-bla1",
"dishNumber": 4,
"dishType": "Type 1"
}, {
"dishName": "bla-bla2",
"dishNumber": 12,
"dishType": "Type 1"
}, {
"dishName": "bla-bla3",
"dishNumber": 2,
"dishType": "Type 2"
}]
},
new_json;
var reorg = function (data) {
var types = [],
dishes = [];
// pass 1, add distinct types
data.dishList.forEach(function (value, index, array) {
if (types.indexOf(value.dishType) === -1) {
// doesn't yet exist
types.push(value.dishType);
}
});
// for each distinct type
types.forEach(function (value, index, array) {
// pass two to n, reorganize based on type
data.dishList.forEach(function (val, i, a) {
if (val.dishType === value) {
// matches dishType
dishes.push({
"dishName": val.dishName,
"dishNumber": val.dishNumber
});
}
});
// redefine value of current array element
array[index] = {
"dishType": value,
"dishes": dishes
};
// reset dishes array
dishes = [];
});
return {
"dishList": types
};
};
new_json = reorg(orig_json);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment