Skip to content

Instantly share code, notes, and snippets.

@dregenor
Created June 1, 2016 09:28
Show Gist options
  • Save dregenor/fdb7cc19c1ab92469ac84bd1615e704a to your computer and use it in GitHub Desktop.
Save dregenor/fdb7cc19c1ab92469ac84bd1615e704a to your computer and use it in GitHub Desktop.
example for reverse array to array
var data = {
"schools" : [
{
"name" : "school a",
"abbvr" : "AED",
"students" : [
{"name" : "a"},
{"name" : "b"}
]
},
{
"name" : "school b",
"abbvr" : "EG",
"students" : [
{"name" : "c"},
{"name" : "d"}
]
},
{
"name" : "school c",
"abbvr" : "ESA",
"students" : [
{"name" : "e"},
{"name" : "f"}
]
}
]
};
var JM = require('json-mapper');
_reduce = function(fn,tail){
return function(input){
if (input instanceof Array){
return input.reduce(fn,tail);
}
return void 0;
}
};
var SimpleSchool = JM.makeConverter({ 'name':'name', 'abbvr':'abbvr'});
var SimpleStudent = JM.makeConverter({ 'name':'name'});
var SchoolConverter = JM.makeConverter({
students : ['schools', _reduce(function(tail,school){
var _simpleSchool = SimpleSchool(school);
if (school.students) {
tail = tail.concat(school.students.map(function(student){
var _simpleStudent = SimpleStudent(student);
_simpleStudent.school = _simpleSchool;
return _simpleStudent;
}));
}
return tail;
},[])]
});
console.log(JSON.stringify(SchoolConverter(data),null,2));
// should be
//{
// "students": [
// {
// "name": "a",
// "school": {
// "name": "school a",
// "abbvr": "AED"
// }
// },
// {
// "name": "b",
// "school": {
// "name": "school a",
// "abbvr": "AED"
// }
// },
// {
// "name": "c",
// "school": {
// "name": "school b",
// "abbvr": "EG"
// }
// },
// {
// "name": "d",
// "school": {
// "name": "school b",
// "abbvr": "EG"
// }
// },
// {
// "name": "e",
// "school": {
// "name": "school c",
// "abbvr": "ESA"
// }
// },
// {
// "name": "f",
// "school": {
// "name": "school c",
// "abbvr": "ESA"
// }
// }
// ]
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment