Answer the question
In order to leave comments, you need to log in
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) key
it does not take the value of variables, but "myValue": value
I 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: (...)
state.table[window.location.href] = value;
Answer the question
In order to leave comments, you need to log in
key does not take the value of variables
const arr = [];
const key = "xxx";
const value = "yyy";
// подробно:
const item = {};
item[key] = value;
// или покороче:
const item = {[key]: value};
// в массив
arr.push(item);
arr // [{xxx: "yyy"} ]
const lsKey = "mytable";
// Сохранить в LS:
localStorage.setItem(lsKey, JSON.stringify(arr));
// Получить из LS:
const arr = JSON.parse(localStorage.getItem(lsKey)) || [];
state.table = {}; // не квадратные, а фигурные
state.table[url] = value;
const arr = []; // массив! Но «в JS всё — объект»
arr.X = "Y"; // можем себе позволить!
console.log(arr.X); // "Y" ура-а, хакнули JavaScript!
JSON.stringify(arr) // [] - пустой массив, облом.
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 questionAsk a Question
731 491 924 answers to any question