M
M
Maxim Timofeev2017-07-19 13:25:16
JavaScript
Maxim Timofeev, 2017-07-19 13:25:16

How to make a basket object in js?

The cart is stored in localStorage, and therefore in the form of json. What structure will be more correct to operate conveniently with data.
At the beginning there was an idea:

product_1: {count:1, title: 'title'},
product_2: {count:1, title: 'title'},
articul_1: {count:1, title: 'title'},

the product and the article are different entities, so don’t delve into it, it doesn’t matter, it’s important that there are several entities and they have id unique for each entity.
It's easy to determine if there is already such an entity in the basket, and so on. But as I found out, js in json does not want to drive it stubbornly.
JSON.stringify(cart); //дает пустой массив
And here is the question: please give a method to drive this into json or poke your nose into another method.
Variant with
0: {item: 'product_1', count:1, title: 'title'},
1: {item: 'product_2', count:1, title: 'title'},
2: {item: 'atricul_1', count:1, title: 'title'},

will not have problems in json, but how to determine the presence and key of an element without pain, for example, we have "product_1" and it is necessary to find in this array whether there is an element with this item. I see only bust, but there must be a more adequate way.
Jammed, for 2 hours I've been walking in circles with a tambourine. Apparently php prevents you from thinking about js.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Morgunov, 2017-07-19
@webinar

You're right, overkill to help. In general, in terms of the client side, enumerations are not so terrible, the browser launches a bunch of threads for its own calculations and does any enumeration quickly enough. It's another matter to save and pull out all this stuff from local storage. It will take more time than searching for values.

M
Maxim Nepritimov, 2017-07-19
@nepritimov_m

Look towards the Immutable.js library .
Retrieving, adding, and checking for the presence of data in an immutable object is pure pleasure.
PS: there is conversion to JSON. The library documentation is excellent.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question