Search code examples
javascriptnode.jsobjectmongooseaggregate

Looping through array of object based on a key and change its value in javascript


Loop through a object array find a key and then change its value in javascript

Hi I have a below array of objects

[
  {
    createdDateTime: {
      '$gte': '2023-02-08T00:00:00.000Z',
      '$lte': '2023-05-09T23:59:59.000Z'
    }
  },
  { user: 'customer' }
]

I want to change it to below

[
  {
    createdDateTime: {
      '$gte':new Date( '2023-02-08T00:00:00.000Z'),
      '$lte':new Date( '2023-05-09T23:59:59.000Z')
    }
  },
  { user: 'customer' }
]

What I tried

var check = filtersFromRequest.some(obj => obj.hasOwnProperty("createdDateTime"));
  if(check){
   // stuck here as what to do , 
  }

Kindly guide


Solution

  • You can loop through the array, and then for each object, check if it has the createdDateTime property. If it does, update the $gte and $lte values with new Date objects.

    Here's how you can do it:

    // Assuming payloads is your initial array
    const updatedPayloads = payloads.map(obj => {
      if(obj.hasOwnProperty('createdDateTime')) {
        let newObject = {...obj}; // clone the object to avoid modifying original
        if(newObject.createdDateTime.hasOwnProperty('$gte')) {
          newObject.createdDateTime['$gte'] = new Date(newObject.createdDateTime['$gte']);
        }
        if(newObject.createdDateTime.hasOwnProperty('$lte')) {
          newObject.createdDateTime['$lte'] = new Date(newObject.createdDateTime['$lte']);
        }
        return newObject;
      } else {
        return obj; // return object as it is if it does not contain 'createdDateTime'
      }
    });
    

    This code will create a new array called updatedPayloads with the date strings replaced by Date objects. The original payloads array will remain unchanged.