I have an array of objects, in the second object I have nested property of ‘request.createdAt’. My issue is how to iterate over this array, in order to reach this property, and parse the date to the same format as seen in the first object.
My last attempt was unsuccessful (returns an array of undefined) and very verbose, but I can’t think of a better way.
arr.map((e) => e.request?.createdAt).filter(item => item).map((x) => e?.request ? e.request.createdAt = Date.parse(x) : null)
Any tips would be appreciated
const arr = [{
"id": 6533118084380,
"public": true,
"attachments": [],
"via": {
"channel": "email",
"source": {
"from": {
"address": "testemail@gmail.com"
}
}
},
"createdAt": 1667804231000,
},
{
"caseFileSlug": "11111111",
"request": {
"id": 1,
"storyParams": {
"preference": "no_backstory"
},
"requestComputed": {
"minAmount": 137,
},
"storyParams": {
"numberOfPeople": 5
},
"createdAt": "2022-11-09 17:26:51 UTC"
}
}]
>Solution :
Map is for making an array with new content. You just need one loop and overwrite the property if it exists.
const arr = [{
"id": 6533118084380,
"public": true,
"attachments": [],
"via": {
"channel": "email",
"source": {
"from": {
"address": "testemail@gmail.com"
}
}
},
"createdAt": 1667804231000,
},
{
"caseFileSlug": "11111111",
"request": {
"id": 1,
"storyParams": {
"preference": "no_backstory"
},
"requestComputed": {
"minAmount": 137,
},
"storyParams": {
"numberOfPeople": 5
},
"createdAt": "2022-11-09 17:26:51 UTC"
}
}]
arr.forEach((record) => {
if (record?.request?.createdAt) {
record.request.createdAt = (new Date(record.request.createdAt)).getTime();
}
})
console.log(arr);
If there is a change it might be a number, you can add a type check.