skip to Main Content

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

3

Answers


  1. 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.

    Login or Signup to reply.
  2. There are so many ways. One is:

    const firstObject = [
      {
        createdDateTime: {
          '$gte': '2023-02-08T00:00:00.000Z',
          '$lte': '2023-05-09T23:59:59.000Z'
        }
      },
      { user: 'customer' }
    ];
    
    const secondObject = firstObject.map(obj => {
      if (obj.createdDateTime) {
        obj.createdDateTime['$gte'] = new Date(obj.createdDateTime['$gte']);
        obj.createdDateTime['$lte'] = new Date(obj.createdDateTime['$lte']);
      }
    
      return obj;
    });
    
    Login or Signup to reply.
  3. You can use Array.forEach()

    filtersFromRequest.forEach( item =>{
        const createdDateTime = item.createDateTime;
        if( createdDateTime ){
            createdDateTime.$gte = new Date(createdDateTime.$gte);
            createdDateTime.$lte = new Date(createdDateTime.$lte);
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search