So I have this array of objects:
[ { type: 'month', value: '9' },
{ type: 'day', value: '11' },
{ type: 'year', value: '2021' },
{ type: 'hour', value: '7' },
{ type: 'minute', value: '35' },
{ type: 'second', value: '07' } ]
I need a way to extract the value 9
using the search term month
.
Sure I could use:
var myObjects = [
{ type: 'month', value: '9' },
{ type: 'day', value: '11' },
{ type: 'year', value: '2021' },
{ type: 'hour', value: '7' },
{ type: 'minute', value: '35' },
{ type: 'second', value: '07' }
] ;
console.log(myObjects[0]["value"]);
Problem is , this is really not using a search term, and I'm in a situation where the date format can change from en_GB
to en_US
and other complicated time formats which will make the month
switch position to [1]
, [2]
or [3]
.
One more variant:
var arr = [{ type: 'month', value: '9' },
{ type: 'day', value: '11' },
{ type: 'year', value: '2021' },
{ type: 'hour', value: '7' },
{ type: 'minute', value: '35' },
{ type: 'second', value: '07' }];
// var month = arr.filter(x => x.type == 'month')[0].value; // less efficient
var month = arr.find(x => x.type == 'month').value; // more efficient
console.log(month) // 9