how to insert data into existing value in localstorage

I have a users key / value saved in local storage looking like this:

users = {
    name: "John",
    email: "jsmith@gmail.com",
    car: []
}

as seen car in the users object is empty.

This is a useState that has a default value of 0 which is used later to get the existing values in localstorage.

const [index, setIndex] = useState(0);

This useState has car features that need to be updated in localstorage.

const [car, setCar] = useState([{
        make: "Lamborghini",
        year: "2020",
        color: "Yellow"
}]);

My problem is with this function, when I pass in the car parameter which is the state value from above, and I get the index value from localstorage which returns correctly the data in storage.

function setCar(car) {
    const cars = getCarsFromStorage(index);
    localStorage.setItem("users", JSON.stringify({index, cars: car}));
}

When I setItem in localstorage to the useState value, the local storage looks like this:

users = {
    index: 0
    cars: [{
        make: "Lamborghini",
        year: "2020",
        color: "Yellow"
    }]
}

Which is not what I want it to look like, instead should look like this:

users = {
    name: "John",
    email: "jsmith@gmail.com",
    car: [{
        make: "Lamborghini",
        year: "2020",
        color: "Yellow"
    }]
}

Would this be possible to do, if so how would I approach this? Any help is appreciated!

Answer

localStorage.setItem("users", DATA) All in DATA will replace what you have in localStorage. “users” is the key DATA is the value.

What you need to do is to get what you have in the localStorage then update values.

Something like that:

function setCar(car) {
    //const cars = getCarsFromStorage(index); // no need this line

    const newDataUsers = JSON.parse(localStorage.getItem("users"));
    newDataUsers.cars = [cars,...newDataUsers.cars];
    localStorage.setItem("users", JSON.stringify(newDataUsers));
}