Reputation: 2785
How can I achieve the below without nested for loops:
invitations
is an array with the following structure:
INVITATIONS:
[{
"id": "TDK4QP788FOLMHQSZAFSYVVQ182RGM83",
"date_created": "2016-11-08T15:37:04.409Z",
"events": [{
"end_time": "21:00",
"start_time": "20:00"
}]
}, {
"id": "DEI4644LAR91SKGUKMR7RTWY3CMC7PCP",
"date_created": "2016-11-08T03:57:11.145Z",
"events": [{
"end_time": "23:45",
"start_time": "06:00"
}]
}]
EVENTS:
[{
"end_time": "23:45",
"start_time": "06:00"
}, {
"end_time": "23:45",
"start_time": "06:00"
}, {
"end_time": "23:45",
"start_time": "06:00"
}, ]
I was thinking to loop over the invitations array, then loop through every events item and then compare that item start and end times to each item in the events array while also looping over the events array.
I think i might be over doing this. Is there another possible way to do this without three or more nested loops?
Thanks in advance.
Upvotes: 1
Views: 3096
Reputation: 27202
Try this i hope it will work :
Here, we have to iterate the invitations
array two times to get the events array elements and created a new array as per the requirement.
Working demo :
var invitations = [{
"id": "TDK4QP788FOLMHQSZAFSYVVQ182RGM83",
"date_created": "2016-11-08T15:37:04.409Z",
"events": [{
"end_time": "21:00",
"start_time": "20:00"
}]
}, {
"id": "DEI4644LAR91SKGUKMR7RTWY3CMC7PCP",
"date_created": "2016-11-08T03:57:11.145Z",
"events": [{
"end_time": "23:45",
"start_time": "06:00"
}]
}];
var events = [];
for (var i in invitations) {
for (var j in invitations[i].events) {
events.push(invitations[i].events[j]);
}
}
document.getElementById("results").innerHTML = JSON.stringify(events);
#results {
font-weight : bold;
}
<div id="results"></div>
Upvotes: -1
Reputation: 565
Using mapping its very easy. See lodash _.map
.
var results = _.map(invitations, 'events');
Can be also achieved in ES6 with
var results = invitations.map(function(invitation) {
return invitation.events;
});
But lodash implementation is faster.
Upvotes: 4