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);
Related
I am saving my products that belong to the shopping cart on the local storage. Everything has the same key. I am using the following code:
for (let i = 0; i<produkt.length; i++) {
.
.
.
document.querySelector('a.produktlöschen'+[i]).addEventListener('click', ()=>{
const parsed = JSON.parse(localStorage.getItem('warenkorb'));
parsed.splice(parsed.indexOf(i), 1);
localStorage.setItem('warenkorb', JSON.stringify(parsed));
location.reload();
the for loop is for the dynamic shopping cart. product1 is i=0, product2 is i=1 ...
My plan is, when the Anchor is clicked, that the product[I] (depends on which Anchor) gets deleted.
With my code, only the last item gets deleted and not the one which anchor is clicked.
let produkt = [
{
name: '3er Set BambuszahnbĂĽrste',
preis: 10,
marke: 'LifePanda',
seit: 2020,
bild_url: '../img/Produkt_1.jpg',
id: 1
},
{
name: 'Nachhaltiges Einkaufsnetz',
preis: 19,
marke: 'GreenEarth',
seit: 2019,
bild_url: '../img/Produkt_2.jpg',
id: 2
}];
Use an OBJECT
You are having problems in referencing (getting the index of) the Array item you wanted to remove. A better way is to directly use an object instead of an Array. This way you can call them using the name you assigned them instead of finding a way to get the index of the item you wanted.
// Using an object you can just directly assign an id that you can call anytime
const obj = {}
obj['a12e'] = {...} // obj = {a12e:{...}} // add new properties
obj.a12e.name = ... // change properties
delete obj.a12e = //delete properties
Do not pull your data from the localStorage
Also, it is better if all the items are stored in an Array of Objects or Objects (depends on your preference). That way, when you remove an item you can remove it from the array and then store the Array into localStorage. Better than having to parse the stringed object and stringifies it again when there is a change into products(this consumes so much time)
Let's compare the concepts then
Changing an Item directly from localStorage: 0# onclick
1# get JSON from localStorage 2# parse JSON to Array 3# remove
item from Array 4# convert Array to stringified JSON 5# store
stringified JSON to localStorage
Changing an Item in an Array/object: 0# onclick 1# remove item from Array/Object 2# convert Array/Object to stringified
JSON 3# store stringified JSON to localStorage
Example
// HTML
<div class=item id=item0><span>Cheese cake </span><button class=remove>x</button></div>
<div class=item id=item1><span>Chocolate cake </span><button class=remove>x</button></div>
<div class=item id=item2><span>Strawberry cake </span><button class=remove>x</button></div>
<div class=item id=item3><span>Double Chocolate cake </span><button class=remove>x</button></div>
// JavaScript
const productItemsObject = {}
localStorage.setItem('products', JSON.stringify(productItemsObject))
for (let items of document.querySelectorAll('.item')) {
productItemsObject[items.id]={name: items.children[0].innerText} // store everything in an object
items.children[1] /*button*/ .addEventListener('click', function() {
//Using an Object
delete productItemsObject[items.id] // remove item from array
localStorage.setItem('productsObj', JSON.stringify(productItemsObject)) // update the data in localStorage only after every change
items.remove()
console.log("Object",localStorage.productsObj)
})
}
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.
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
I'm trying to .map through data returned from an API (the NASA API). The issue I'm having is with deeply nested properties -- here's an example.
What's the best way to get the nested name and estimated_diameter properties data in React? All the data's being brought in just fine via axios. Logging out the state returns this:
I'm having trouble map'ing through the data because of the nested objects and arrays.
Assume the nasa data json is saved in the variable nasaData, the code below will print all the name and the estimated_diameter
var nearEarthObjects = nasaData['near_earth_objects'];
for (var property in nearEarthObjects) {
if (nearEarthObjects.hasOwnProperty(property)) {
var data = nearEarthObjects[property];
data.forEach(function(d){
console.log(d['name']);
console.log(d['estimated_diameter']);
});
}
}
ps: this might be for a reactjs project but it's really just javascript
You can map through the dates first.
const { near_earth_objects } = nasaData; //assuming nasaData is the json object
const dateKeys = Object.keys(near_earth_objects);
const nameAndEstimatedDiameters = dateKeys.map((dateKey) => {
const dateData = near_earth_objects[dateKey];
const { name, estimated_diameter } = dateData;
return { name, estimated_diameter };
});
//now nameAndEstimatedDiameters is an array of objects here
//which you can map again
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];