Reputation: 113
I have a list of months in JSON, want to select the current month from the list in React Native.
Here is my list:
Month: [
{ value: "1", label: "JAN", key: "JAN" },
{ value: "2", label: "FEB", key: "FEB" },
{ value: "3", label: "MAR", key: "MAR" },
{ value: "4", label: "APRIL", key: "APRIL" },
{ value: "5", label: "MAY", key: "MAY" },
{ value: "6", label: "JUN", key: "JUN" },
{ value: "7", label: "JUL", key: "JUL" },
{ value: "8", label: "AUG", key: "AUG" },
{ value: "9", label: "SEP", key: "SEP" },
{ value: "10", label: "OCT", key: "OCT" },
{ value: "11", label: "NOV", key: "NOV" },
{ value: "12", label: "DEC", key: "DEC" }
];
Upvotes: 0
Views: 1136
Reputation: 45865
By doing as below, you get the current month mapped to the one inside your array:
let Month = [
{ value: "1", label: "JAN", key: "JAN" },
{ value: "2", label: "FEB", key: "FEB" },
{ value: "3", label: "MAR", key: "MAR" },
{ value: "4", label: "APRIL", key: "APRIL" },
{ value: "5", label: "MAY", key: "MAY" },
{ value: "6", label: "JUN", key: "JUN" },
{ value: "7", label: "JUL", key: "JUL" },
{ value: "8", label: "AUG", key: "AUG" },
{ value: "9", label: "SEP", key: "SEP" },
{ value: "10", label: "OCT", key: "OCT" },
{ value: "11", label: "NOV", key: "NOV" },
{ value: "12", label: "DEC", key: "DEC" }
];
let currentMonth = Month[new Date().getMonth()];
console.log(currentMonth);
Upvotes: 1
Reputation: 72
You can find the current month index using
const currentMonthIndex = new Date().getMonth() + 1
Month usually start from 0 so you have to add 1 Then you can filter through the array
const selectedMonth = months.find(m => m.value === currentMonthIndex)
Upvotes: 1