I have a javascript array. Something like this one:
let myObjects = [{
'name': 'name 1',
'date': '2017-04-15T22:00:00Z',
'date2': '2017-04-12T22:00:00Z' },
{ 'name': 'name 2',
'date': '2017-04-05T22:00:00Z' },
{ 'name': 'name 3',
'date': '2017-04-05T22:00:00Z' },
{ 'name': 'name 4',
'date': '2017-04-12T22:00:00Z',
'date2': '2017-04-10T22:00:00Z' }];
I want to order myObjects
by date2
, but in case that the object does not have this attribute, it should be considered its date
value.
I could just do it this way:
myObjects.map(function(obj){ if(!obj.date2){ obj['date2'] = obj['date']; }});
let orderedObjects = _.orderBy(myObjects, 'date2', true);
But I consider that it is a tricky solution. Could this be done just using the orderBy
function without altering the original array?