Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

map over an array to find a value and return the object

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading