简体   繁体   中英

Just trying to store 6 array values into localStorage

The array oldData [] holds 6 values. (integer values fetched from api). All I want to do is put these values in 1 localStorage key called 'olddata'.

I've searched everywhere and didn't find anything that make this work. Could please someone help me with a simple solution?

The way I'm trying now:

        let oldData = [];
        oldData.push(parkingData.availableCapacity);
        console.log(oldData); // Definitely holds 6 values 
        localStorage.setItem('olddata', oldData); // Only stores the last value 
        of oldData

Also tried a few loops but didn't succeed.

localStorage only stores strings.

Use JSON.stringify() to set an array as string and JSON.parse() to parse that same string back to array when you retrieve the data

 localStorage.setItem('olddata', JSON.stringify(oldData));
let url = 'https://datatank.stad.gent/4/mobiliteit/bezettingparkingsrealtime.json#';
let percent;
let mainDiv = document.getElementById('mainDiv');


function fetchParkingData() {
fetch(url)
.then((resp) => resp.json())
.then(function(data) {

    mainDiv.innerHTML = "";
    for(let i = 0; i < data.length; i++) {

        let parkingData = {
            name: data[i].name,
            totalCapacity: data[i].parkingStatus.totalCapacity,
            availableCapacity: data[i].parkingStatus.availableCapacity,
        }


        let oldData = [];
        oldData.push(JSON.parse(parkingData.availableCapacity));
        console.log(oldData);
        // console.log(oldData.join());
        localStorage.setItem('dataObject', JSON.stringify(oldData));
    };
})

.catch(function(error) {
    // error handling
    parkingDiv.innerHTML = 'Data could not be fetched';
});
}

Browser console commands and output here:

>let oldData = [];
undefined
>oldData.push('1st Value');
1
>oldData.push('2nd Value');
2
>oldData.push('3rd Value');
3
>console.log(oldData);
(3) ["1st Value", "2nd Value", "3rd Value"]
undefined
>localStorage.setItem('oldData', JSON.stringify(oldData));
undefined
>JSON.parse(localStorage.getItem('oldData'));
(3) ["1st Value", "2nd Value", "3rd Value"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM