Z
Z
zjoin2017-02-04 23:12:50
JavaScript
zjoin, 2017-02-04 23:12:50

How to make an object counter in localStorage?

Hello everyone, in general, you need to write an array of objects in localStorage, how to make sure that every time the page is updated, a counter property is created in the object, instead of adding to the previous array.
So that when the page is updated, let's say three times it was not so in localStorage -

[{"id":1,"obj_id":234,"count":0},{"id":1,"obj_id":234,"count":0},{"id":1,"obj_id":234,"count":0}]

And so [{"id":1,"obj_id":234,"count":3}]
That is, the value of the count property changed every time the page was updated
https://jsfiddle.net/m3L287gd/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2017-02-05
@zjoin

var keyName = 'my_counter'
var emptyCounter = [{"id":1,"obj_id":234,"count":0}]
var myObject = JSON.parse(localStorage.getItem(keyName)) || emptyCounter
myObject[0].count++
localStorage.setItem(keyName, JSON.stringify(myObject));

https://jsfiddle.net/ctpsxzan/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question