So I have a series of dates as such:
const accumulatedDates = ['2023-08-22', '2023-08-23', '2023-08-24']
and I have an object which contains the following:
const orderDataByDate = {2023-08-23: 1321, 2023-08-24: 2}
What i am trying to achieve is to map over accumulatedDates
to find the value from orderDataByDate
to build up an array. If it can be found, then return it in an object form like so {2023-08-23: 1321}
, and if it cant be found, then return the value as zero i.e. {2022-08-23: 0}
The end result should something like this:
const results = [
{2023-08-22: 0},
{2023-08-23: 1321},
{2023-08-24: 2}
]
What I have tried so far is:
const results = accumulatedDates.map(date =>
Object.keys(orderDataByDate).filter(key =>
key === date
? {
date: orderDataByDate[key]
}
: {
date: 0
}
)
)
but not getting the desired result. The result i get is:
[
['2023-08-23', '2023-08-24']
['2023-08-23', '2023-08-24']
['2023-08-23', '2023-08-24']
]
which is completely off target to what im trying to achieve.
3
Answers
Use
reduce()
where you create a object with the keys fromaccumulatedDates
and the value asorderDataByDate[c] || 0
which will use0
as a fallback if the key is not found in the objectYou could take the entries and build an object.
A trick is to use the
{[varname]: value}
syntax to allow you to use a variable as the key. E.g:This should give you an array with objects a la