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.
>Solution :
You could take the entries and build an object.
const
accumulatedDates = ['2023-08-22', '2023-08-23', '2023-08-24'],
orderDataByDate = { '2023-08-23': 1321, '2023-08-24': 2 },
result = Object.fromEntries(accumulatedDates.map(d => [d, orderDataByDate[d] || 0]));
console.log(result);