[Fixed] How to reassign values of a nested (read only) object in ES6?

Issue

I have a read only object of travelers with this format:

{
    "teens": {
        "count": 2,
        "persons": {
            {
                "age": "13",
                "name": "Carey",
                "surname": "Price",
                "birth_date": "05-04-2007",
            },
            {
                "age": "14",
                "name": "Isaias",
                "surname": "Beahan",
                "birth_date": "01-24-2007",
            },
        },
    },
    "adults": {
       "count": 1,
       "persons": {
            {
                "age": "31",
                "name": "Effie",
                "surname": "Bednar",
                "birth_date": "04-19-1989",
            }
       },
    },
}

And I need change the format of the birth_date of each person to YYYY-MM-DD format. Here’s my attempt:

Object.entries(travelers).forEach(([key, value]) => {
    return value.persons.map((person: IPersonJSON) => {
        return {
            ...person,
            birth_date: new Date(person.birth_date).toString().slice(0, 10),
        };
    });
});

console.log(travelers);

However on logging the travelers, the original object is unchanged. What am I missing here?

EDIT:

Here’s an attempt to clone the object and reassign those values:

const copy = Object.assign({}, travelers);
            
Object.entries(copy).forEach(([key, value]) => {
    value.persons.forEach(person => {
        person.birth_date = new Date(person.birth_date).toISOString().slice(0,10);
    });
});

console.log(copy);

I still get this error: Cannot assign to read only property 'birth_date' of object '[object Object]'

Solution

In the ‘travelers’ object, the nested key ‘persons’ should be an array like this –

"persons": [
        {
            "age": "13",
            "name": "Carey",
            "surname": "Price",
            "birth_date": "05-04-2007",
        },
        {
            "age": "14",
            "name": "Isaias",
            "surname": "Beahan",
            "birth_date": "01-24-2007",
        },
     ]

Then to update format of birth_date of each person, you can use following code –

Object.entries(travelers).forEach(([key, value]) => {
    value.persons.forEach(person => {
         person.birth_date = new Date(person.birth_date).toISOString().slice(0,10);
    });
});

Leave a Reply

(*) Required, Your email will not be published