Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling function on a nested Objects property?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading