1

I am currently working on a project using geolocation. Every 30 seconds, the current location was retrieved from GeoLocation and saved to LocalStorage. I want to concat the stored objects into an array. How do I do this?

    const lastIndex = localStorage.getItem("lastIndex");
    const endLocation = JSON.parse(localStorage.getItem("location"+lastIndex));

    let map = [];

    for(let i = 0 ; i <= lastIndex ; i++) {
        map.concat(JSON.stringify(localStorage.getItem("location"+i)));
        localStorage.removeItem("location"+i);
    };

This is my code. enter image description here

In other words, I want to return a new object by putting the location object through the map array.

For example - map = [{"lng" : "37.12345", "lat" : "13.12345", "timestamp" : "12141251121212"},

{"lng" : "37.12345", "lat" : "13.12345", "timestamp" : "12141251121212"},

{"lng" : "37.12345", "lat" : "13.12345", "timestamp" : "12141251121212"} ]

But what comes out is null, what should I do?

1 Answer 1

1

concat returns the new array, it doesn't modify the array you call it on. You aren't using that return value, so you don't see the combined result.

Also, since concat returns a new array each time, it's probably not a great choice for this. Just use push:

const map = [];
for (let i = 0; i <= lastIndex; ++i) {
    const key = "location" + i;
    map.push(JSON.parse(localStorage.getItem(key));
    localStorage.removeItem(key);
}
// Use `map` here...

Note that you were using JSON.stringify where you wanted JSON.parse.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.