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
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:
This code will create a new array called
updatedPayloads
with the date strings replaced by Date objects. The originalpayloads
array will remain unchanged.There are so many ways. One is:
You can use Array.forEach()