localStorage ReactJs not working while push - javascript

I just tried to store array data inside localStorage with ReactJs.
Code Below :
storeData(){
const datas = {
name : this.state.prevName,
id : Date.now()
}
var localDatas = localStorage.getItem('names');
if(!localDatas){
localStorage.setItem('names',JSON.stringify(datas));
}else{
var items = [];
items = JSON.parse(localStorage.getItem('names'));
items.push(datas);
localStorage.setItem('names',JSON.stringify(items));
}
}
It's working first time when undefined localDatas variable. I mean when there is no names set at localStorage.
if running for first time And whenever i tried to push new data then its generate error.
Error Below :
TypeError: items.push is not a function
}else{
68 | var items = [];
69 | items = JSON.parse(localStorage.getItem('names'));
> 70 | items.push(datas);
71 | ^ localStorage.setItem('names',JSON.stringify(items));
72 | }
73 | }
How to solve this ?

When first localDatas is undefined, it sets the localStorage item as an object, not array.
Second time this function is called, items is an object and not an array and therefore no .push for him.
var items = []; // items is array
items = JSON.parse(localStorage.getItem('names')); // items is now OBJECT!!
items.push(datas); // can't do a .push to an object
localStorage.setItem('names',JSON.stringify(items));
You could just make datas an array and everything should work.
const datas = [{
name : this.state.prevName,
id : Date.now()
}]
FIX:
Since datas is now an array and we want to push only the object inside, instead of:
items.push(datas); should be: items.push(datas[0]);

The problem is that JSON.parse is returning an object (not an array). As an object it does not have any "push" method.
You could fix this by making sure "datas" is starting as an array :
let storeData = () => {
const datas = [{
name : this.state.prevName,
id : Date.now()
}]
var localDatas = localStorage.getItem('names');
if(!localDatas) {
localStorage.setItem('names',JSON.stringify(datas));
} else {
var items = [];
items = JSON.parse(localStorage.getItem('names'))
items.push(datas);
localStorage.setItem('names',JSON.stringify(items));
}
}

The JSON.parse function returns an object if the string passed to it represents a JSON object, and an array if the string represents a JSON array. If you're using window.localStorage.getItem('names') to retrieve data from local storage and JSON.parse() to parse that data, the type of data returned will depend on the string stored in local storage. From your code, you passed on to the local storage, which is the datas.
If you want to ensure that you get an array, you can modify the data stored in local storage to be a JSON string representing an array like this:
window.localStorage.setItem('data', JSON.stringify([datas]))
In that case
data = JSON.parse(window.localStorage.getItem('data'))
will return array for you to perform push and other array functions.

Related

JSON parse returns empty string?

I am not sure if this is an issue about VueJS or JS itself.
I have string in my DB (converted JS Object with JSON.stringify() ) which looks like this:
{"type":5,"values":{"7":"/data/images/structured-content/64-7-scico.jpg","8":"<b>wefwe</b>","9":"Nějaký text","10":"/data/images/structured-content/64-10-scico.jpg"}}
What I wanted to do is select it from database (via Axios), convert it back to JS object and set it to VueJS data:
.then(response => {
if (response.data.response === "ok" && response.status == 200) {
// get data
let data = response.data.data.data[0];
// pass name to state
this.objectName = data.name;
// get json in string format
let result = data.content;
// first log
console.log(result);
// convert string to json
let content = JSON.parse( result );
// second log
console.log( content.values );
// update states
this.IDType = content.type;
this.values = content.values;
}
})
Axios, data.name and content.type works fine, however the second log (content.values) seems to be returning observer with empty strings which I can't pass to Vue data and work with it, as you can see on the screen below, values in this object are just empty no matter what I do.
What is exactly wrong in here? Thank you!
from debugger:
To be reactive Vue needs to know what the keys of an object are before you assign them. So if they are known, pre assign them:
data : () => ({
values : {
7 : "",
8 : "",
9 : "",
10 : ""
}
}),
Then use object assign to set them:
Object.assign(this.values, content.values)
If the keys are unknown / dynamic values you can set them to be reactive using the $set method:
Object.keys(content.values).forEach(
function(key){
this.$set(this.value, key, content.values[key])
}
)

How to fetch values from json array object without using object key name javascript?

Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc

LocalStorage Setting Object Inside Array Ionic List

I am trying to use LocalStorage to store an array that contains objects. Right now the following code is returning an object on the console and not returning as an array. This means that my ion-list cannot read it. Is there any way around this and getting back the value as an array with my objects in the array? The object presentation contains multiple things such as ID, title, etc etc. I want to be able to store multiple presentations in the array and be able to access each one and display them in the ion list.
Manager.js
playlistService.addPlaylistAll = function (presentation) {
console.log("setting item");
var playlistarraytest = [];
playlistarraytest.push(presentation);
console.log("array first!! ", playlistarraytest);
localStorage.setItem('playlisttest', playlistarraytest);
playlistService.refresh();
var test = localStorage.getItem('playlisttest');
console.log(test);
}
Playlist.html
<ion-list ng-repeat="presentation in dayOne = (playlist | filter: { day: 1 } | orderBy: 'start_date')">
You cannot store data structures directly in LocalStorage. LocalStorage only stores strings. So you must use:
let json = JSON.stringify(playlistarraytest);
localStorage.setItem('playlisttest', json);
And then to retrieve it use:
var test = localStorage.getItem('playlisttest');
let arr = JSON.parse(test);
console.log(arr);

OOP get this key value of object array

So close to nailing this but falling at the last hurdle... Need some clarification.
Basically, I want to load in the array value of a key in a given object as a variable, if other variable strings match.
Perhaps it's better if I give it some context:
js:
var ArraysObject = {
"new" : [
"http://productPageBanners/UK/2new/c0bkn201001u0000.jpg",
"http://productPageBanners/UK/2new/h0ihd60100000001.jpg",
"http://productPageBanners/UK/2new/l0flj20100000001.jpg",
"http://productPageBanners/UK/2new/m0lrt60100000001.jpg",
"http://productPageBanners/UK/2new/p0gps50106000001.jpg"
],
"knives" : [
"http://productPageBanners/UK/3aknives/c0bkn201001u0000.jpg",
"http://productPageBanners/UK/3aknives/n01pl20100000001.jpg"
]
};
var url = jQuery(location).attr('href'); // get the current url, outputs URL
var icatRef = url.split("/")[4]; // capture the icatRef from url, outputs ==>"knives"
// Get properties on the object ArraysObject as an array
var icatTitlesInObject = Object.keys(ArraysObject); // outputs the keys in object, i.e ==> ["new","knives"]
Then I want to check that if the indexOf that array is equal to the icatRef (pulled from the URL), then create a new variable which stores the relevant array from the correct key.
Something like:
if (icatsArray.indexOf() == icatRef) {
var currentarraytorandomise = ArraysObject.keys.this};
// if "knives" is the icatRef then currentarraytorandomise ==> [
// "http://productPageBanners/UK/3aknives/c0bkn201001u0000.jpg",
// "http://productPageBanners/UK/3aknives/n01pl20100000001.jpg"
// ]
However that last bit is wrong because currentarraytorandomise is undefined.
I hope that's clear! Quite new to OOP.
You're using indexOf incorrectly, try something like this:
var currentarraytorandomise, index = icatsArray.indexOf(icatRef);
if (index >= 0) {
currentarraytorandomise = ArraysObject[icatsArray[index]];
}
But you could just try to get the array directly:
ArraysObject[icatRef]
Without extracting keys or anything. If icatRef doesn't exist, you'll get undefined.

when saving an array of objects as a JSON, I need to use the following format in Sample.txt to not run into parsing errors:

when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...

Categories