I am trying to modify the dates in an object in below format. Basically I want to first convert the string date into date format, then try to get the year and decide if it’s 1st half of the year i.e. from 2023.01.01 to H1′ 2023 or 2nd half of the year i.e. from 2023.07.01 to H2’2023 and then update the dates. Really appreciate your help Thanks
// Current Data set
data = [{'description': 'halfyear', date: '2024.01.01'},
{'description': 'halfyear', date: '2024.07.01'},
{'description': 'halfyear', date: '2016.01.01'},
{'description': 'halfyear', date: '2016.07.01'}
]
// Expected Data
data = [{'description': 'halfyear', date: 'H1'2024'},
{'description': 'halfyear', date: 'H2'2024'},
{'description': 'halfyear', date: 'H1'2016'},
{'description': 'halfyear', date: 'H2'2016'}
]
I have tried below but it doesn’t seem to update correctly and override the values.
data.map(x=> {
return x.formatted = 'H' + ' ' + new Date(x.date).getMonth() + 1 < 6 ? '1': '2' + new Date(x.date).getFullYear() + ''
})
Current Data- https://phpout.com/wp-content/uploads/2023/06/jX9EK.png
Expected Result: https://phpout.com/wp-content/uploads/2023/06/7tcMO.png
2
Answers
To avoid confusion while managing brackets and operator precedence I would recommend using template literals. Also you don’t need to add to the month
1
since the math is already working (< 6
).It’s inefficient to parse the string to a Date just to call a method to get back the month value when it’s available directly from the string. It’s particularly problematic to use the built–in Date parser with an unsupported string format.
To modify the value of the date property based on the month, just parse out the month and see if it’s
< 7
. E.g.