I need to add year, month, day for my object. This is my current string array
JavaScript
x
2
1
["2021-11-01","2021-11-02"]
2
I need to convert this as below
JavaScript
1
2
1
[{ year: 2021, month: 11, day: 01 }, { year: 2021, month: 11, day: 02 }]
2
How i do this conversion. thank you
Advertisement
Answer
Just split()
the date into components, map()
the strings to numbers using parseInt()
, and create an object:
JavaScript
1
8
1
const data = ["2021-11-01","2021-11-02"];
2
3
const result = data.map(d => {
4
const [year, month, day] = d.split('-').map(v => parseInt(v));
5
return {year, month, day};
6
});
7
8
console.log(result);