skip to Main Content

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


  1. Use reduce() where you create a object with the keys from accumulatedDates and the value as orderDataByDate[c] || 0 which will use 0 as a fallback if the key is not found in the object

    const accumulatedDates = ['2023-08-22', '2023-08-23', '2023-08-24']
    
    const orderDataByDate = { '2023-08-23': 1321, '2023-08-24': 2};
    
    
    const res = accumulatedDates.reduce((p, c) => ({ ...p, [c]: orderDataByDate[c] || 0 }), {});
    
    console.log(res)
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
  3. A trick is to use the {[varname]: value} syntax to allow you to use a variable as the key. E.g:

    accumulatedDates.map(date => {
      return {[date]: orderDataByDate[date] || 0}
    })
    

    This should give you an array with objects a la

    const results = [
       {2023-08-22: 0},
       {2023-08-23: 1321},
       {2023-08-24: 2}
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search