How to store value in localStorage with certain format - javascript

how can I have a localStorage value stored as
I have the value as:
ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew
but its like it has an arrow to expand and shows the same value only without the {}, an also how do I insert those keys with the slash and 2dots, have the value inside "", I thought it was an object but after trying to insert the value in a variable
var lsvalue = {
/: "ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew",
}
localStorage.setItem('rmStore', JSON.stringify(lsvalue))
but it did not work, any thoughts?
tried to code mentioned

Store it as a string, the debug tool is automatically interpreting this as an object.
var lsvalue = '{"/":"ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew"}';
localStorage.setItem( 'rmStore', lsvalue )

If I'm understanding this correctly, you want your value to be just this string: "ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew".
So, you can just assign that string alone to lsvalue, and set it to localStorage:
var lsvalue = "ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew";
localStorage.setItem('rmStore', lsvalue);
Or just set that string as the value:
localStorage.setItem('rmStore', 'ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew');
Both of the above solutions result in the below:
But, if you're looking to set an object to localStorage:
var lsvalue =
{
'storedObject' : "ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew"
}
localStorage.setItem('rmStore', JSON.stringify(lsvalue));
This setup results in the below:

Related

How do I set multiple values of a JSON object?

So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply

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

javascript - JSON file use a value only if key exists

I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. Since the data are very different from one another (for example, some of them do have a a tag called "addr:city", and some of them not), I would like to check if a key exists, and only in that case save the corresponding value. I've found only this question but it's not my case, since I do not know a priori which keys one element will have and which not, and since I'm working with a great load of data, I really can't check the elements one by one and of course I can't write an IF for each case.
Is there a way to solve this? I was thinking something about "if key has null value, ignore it", while looping over the elements, but I don't know if something like that exists
EDIT:
This is my query:
https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696);way[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696););out%20center;
and this is the code I'm using to save the data on firebase:
results.elements.forEach(e=>{
var ref = firebase.database().ref('/point_of_interest/');
var key = firebase.database().ref().child('point_of_interest').push().key;
var updates = {};
var data = {
città: e.tags["addr:city"],
tipologia: e.tags["amenity"],
indirizzo: e.tags["addr:street"],
nome: e.tags["name"],
lat: e.lat,
lon: e.lon
}
updates['/point_of_interest/'+key] = data;
firebase.database().ref().update(updates);
})
"results" is the response in json format
You could use something like that:
var attrs = ["addr:city", "amenity", "addr:street", "name"];
var labels = ["città", "tipologia", "indirizzo", "nome"]
var data = { };
attrs.forEach((a, i) => {
if (e.tags[a]) { data[labels[i]] = e.tags[a]; }
});
You could even make this more dynamic, if you can query the attribute names and labels from somewhere.

Delete a field from Firestore, with a dynamic key

I am trying to delete a single field from a Document in Firestore
The Key of the field is held in a variable e.g.
var userId = "random-id-1"
In the document I have a field of members structured like this:
{
members:{
random-id-1:true,
random-id-2:true
}
}
I would like to delete random-id-1:true, but keep random-id-2:true
How is this possible without getting the entire members object and writing an updated object?
I have tried this, however I get the error: Document references must have an even number of segments
and I also tried this:
db.collection('groups').doc(this.props.groupId).set({
members: {
[userId]: firebase.firestore.FieldValue.delete()
}
},{merge: true})
However I get the error: Function DocumentReference.update() called with invalid data. FieldValue.delete() can only appear at the top level of your update data
Thanks for any help
I have managed to delete a field like this:
let userId = "this-is-my-user-id"
let groupId = "this-is-my-group-id"
db.collection('groups').doc(groupId).update({
['members.' + userId]: firebase.firestore.FieldValue.delete()
})
This is using the dot operator method described here
Please let me know if there are any alternative methods to this
Thanks
I had to import FieldValue
https://firebase.google.com/docs/firestore/manage-data/delete-data#fields
// Get the `FieldValue` object
var FieldValue = require('firebase-admin').firestore.FieldValue;
// Create a document reference
var cityRef = db.collection('cities').doc('BJ');
// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
capital: FieldValue.delete()
});

Store values in javascript object with same keys

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"];

Categories