A
A
Artem Prokhorov2021-06-16 21:50:43
JavaScript
Artem Prokhorov, 2021-06-16 21:50:43

Is it possible to save an object property to localStorage array?

There is an array table = []for the cache, I want to add data like key: obj.
The point is that the method push()does add an object to the end of the array, but it numbers the keys in order.
It does not suit me, because I need to know what to refer to. If you use push({ key: value }), then there are already 2 problems
1) keyit does not take the value of variables, but "myValue": valueI cannot conditionally set it statically, since all properties will have the same keys.
2) Yes, and in this case, if I enter a constant value there with text (test is acceptable), then I get such a nesting:

6:
test: Object
items: (...)
_links: (...)
_meta: (...)


That is, the name is permanent, which is already, as it were, past, so it’s still useless if you have to turn to the six.

But if you add via: Then it is added to the array, but, drum roll ... it is not written to localStorage. How to fix it?
state.table[window.location.href] = value;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2021-06-16
@kotcich

key does not take the value of variables
Accepts.
const arr = [];

const key = "xxx";
const value = "yyy";

// подробно:
const item = {};
item[key] = value; 

// или покороче:
const item = {[key]: value};

// в массив
arr.push(item);
arr // [{xxx: "yyy"} ]

entry in LS
const lsKey = "mytable";

// Сохранить в LS:
localStorage.setItem(lsKey, JSON.stringify(arr));

// Получить из LS:
const arr = JSON.parse(localStorage.getItem(lsKey)) || [];

Upd. in general, declare not an array, but an object:
state.table = {}; // не квадратные, а фигурные

state.table[url] = value;

PS Yes, an array is an object, and you can assign left properties to it. But that's bad. If only because when serialized to JSON, all left properties will disappear:
const arr = [];     // массив! Но «в JS всё — объект»
arr.X = "Y";        // можем себе позволить!
console.log(arr.X); // "Y" ура-а, хакнули JavaScript!

JSON.stringify(arr) // [] - пустой массив, облом.

A
Alexey Yarkov, 2021-06-16
@yarkov

Will we see the entry code in LS?
Just in case, I remind you that only strings can be stored there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question