I have an array like so where each 'category' value is a string in the format "YYYY-MM-DD':
let originalData = [
{
"category": "2017-07-24",
"total": 1,
"Col 1": 200
},
{
"category": "2018-07-10",
"total": 1,
"Col 1": 100
},
{
"category": "2018-11-12",
"total": 1,
"Col 1": 101
},
{
"category": "2019-08-11",
"total": 1,
"Col 1": 153
},
{
"category": "2019-09-11",
"total": 1,
"Col 1": 198
}
]
How can I convert it so that the "category value" is as follows for each object?
let desiredResult = [
{
"category": new Date(2017, 7, 24).getTime(),
"total": 1,
"Col 1": 200
},
{
"category": new Date(2018, 7, 10).getTime(),
"total": 1,
"Col 1": 100
},
{
"category": new Date(2018, 11, 12).getTime(),
"total": 1,
"Col 1": 101
},
{
"category": new Date(2019, 8, 11).getTime(),
"total": 1,
"Col 1": 153
},
{
"category": new Date(2019, 9, 11).getTime(),
"total": 1,
"Col 1": 198
}
]
Bear in mind that the values in the original "category" key has the months and dates listed such that there is a 0 in singular dates: "2017-07-24" i.e. there's a 0 before 7 in the MM section. However, new Date(2017, 7, 24) does not work if you do something like new Date(2017, 07, 24), it has to be singular.
I know I can do something like
this.originalData.forEach( item => {
// somehow retrieve the specific sections in that item's category
item.category = new Date(..??..).getTime()
})
However, I'm unsure as to how to filter it so that it we get new Date(YYYY-MM-DD) WHILE removing any 0s before any month or day with a singular number e.g.
2017-08-08 would be new Date(2017, 8, 8).getTime() 2013-09-22 would be new Date(2013, 9, 22).getTime() etc.
CodePudding user response:
const originalData = [{category: '2017-07-24',total: 1,'Col 1': 200,},{category: '2018-07-10',total: 1,'Col 1': 100,},{category: '2018-11-12',total: 1,'Col 1': 101,},{category: '2019-08-11',total: 1,'Col 1': 153,},{category: '2019-09-11',total: 1,'Col 1': 198,},]
const result = originalData.map((x) => {
return {...x, category: new Date(x.category).getTime()};
});
console.log(result);
CodePudding user response:
You can do:
const originalData = [{category: '2017-07-24',total: 1,'Col 1': 200,},{category: '2018-07-10',total: 1,'Col 1': 100,},{category: '2018-11-12',total: 1,'Col 1': 101,},{category: '2019-08-11',total: 1,'Col 1': 153,},{category: '2019-09-11',total: 1,'Col 1': 198,},]
const result = originalData.map((item) => ({
...item,
category: Date.parse(item.category)
}))
console.log(result)