I've the following complex JSON object that has got array and array inside an array. How can parse those arrays and create an object array for each element in the array. I'm using lodash library in my project, just in case if there are any functions available.
{
studentId: 123
name: XYZ
phone: 34234234
gender: M
subjects: [{
studentId: 123
subjectName: Math
scores:50
assignments:[
{
type: Internal,
submitted: yes,
status: failed
},
{
type: External,
submitted: yes,
status: passed
}]
},
{
studentId: 123
subjectName: Science
score: 20
assignments:[
{
type: Internal,
submitted: yes,
status: passed
},
{
type: External,
submitted: yes,
status: failed
}]
}]
}
Expecting:
[{
studentId:123,
name: XYZ
phone: 34234234
gender: M,
subjectName: Math
scores:50
assignments:[
{
type: Internal,
submitted: yes,
status: failed
},
{
type: External,
submitted: yes,
status: passed
}]
},
{
studentId:123,
name: XYZ
phone: 34234234
gender: M,
subjectName: science
scores:20
assignments:[
{
type: Internal,
submitted: yes,
status: failed
},
{
type: External,
submitted: yes,
status: passed
}]
}
]
You can use omit to get the details
of the student without the subjects
array, use these details
to transform each item in the subjects array using defaults through map .
var details = _.omit(data, 'subjects');
var result = _.map(data.subjects, function(subject) {
return _.defaults({}, details, subject);
});
var data = { studentId: '123', name: 'XYZ', phone: '34234234', gender: 'M', subjects: [{ studentId: '123', subjectName: 'Math', scores: 50, assignments: [{ type: 'Internal', submitted: 'yes', status: 'failed' }, { type: 'External', submitted: 'yes', status: 'passed' } ] }, { studentId: '123', subjectName: 'Science', score: 20, assignments: [{ type: 'Internal', submitted: 'yes', status: 'passed' }, { type: 'External', submitted: 'yes', status: 'failed' } ] } ] }; var details = _.omit(data, 'subjects'); var result = _.map(data.subjects, function(subject) { return _.defaults({}, details, subject); }); console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
I encourage you to use Normalizr package. It's very useful and takes all care about your collections even if they're nested.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.