Reputation: 79
I am trying to unnest an array currently using this code:
var mapped = _.flatMap(payload, ({GroupId,Learners}) =>
_.map(Learners, LearnerId => ({GroupId:GroupId,Learner:LearnerId}))
);
however the value return still produces and array: e.g
{"GroupId":1246574,"Learner":{"Forename":"George","Surname":Bob",,"StartDate":"2020-09-01","EndDate":"2021-08-27"}}
How can I adapt the script above to only return the GroupId and the Surname?
Example of the payload is here:
var payload =
{
"GroupId": 1208864,
"Code": "Ext-StuOth",
"GroupType": "AcademicHouseGroup",
"Learners": [
{
"LearnerId": 245218,
"LearnerCode": "2009-0017",
"Forename": "Sanelisiwe",
"Surname": "Nazi-Angileh",
"LearnerGroupLearnerId": 14719301,
"StartDate": "2017-03-09",
"EndDate": null
},
{
"LearnerId": 246638,
"LearnerCode": "2013-0076",
"Forename": "Randal",
"Surname": "Bodziarczyk",
"LearnerGroupLearnerId": 14650361,
"StartDate": "2017-02-20",
"EndDate": null
},
{
"LearnerId": 245253,
"LearnerCode": "109056",
"Forename": "Wafah",
"Surname": "Dadisman",
"LearnerGroupLearnerId": 14650360,
"StartDate": "2017-02-20",
"EndDate": null
}
},{
"GroupId": 1226419,
"Code": "U6-JD",
"GroupType": "RegistrationGroup",
"Learners": [
{
"LearnerId": 245507,
"LearnerCode": "110015",
"Forename": "Nahomy",
"Surname": "Osburn",
"LearnerGroupLearnerId": 14918706,
"StartDate": "2017-09-07",
"EndDate": "2018-07-31"
},
{
"LearnerId": 245994,
"LearnerCode": "111624",
"Forename": "Sherhona",
"Surname": "Dobritoiu",
"LearnerGroupLearnerId": 14707593,
"StartDate": "2017-08-01",
"EndDate": "2018-07-31"
}
}
Upvotes: 0
Views: 108
Reputation: 26806
You can access access the elements as following:
console.log(payload.GroupId);
var learners = payload.Learners;
learners.forEach(function(learner){
console.log(learner.Surname);
Upvotes: 0
Reputation: 445
var result = _.flatMap(payload, ({GroupId, Learners}) => {
return _.map(Learners, learner => ({GroupId, LearnerId: learner.LearnerId}))
})
Upvotes: 1