how to show data after parse json - javascript

I try to load the list of users in the following code
<div id="users" data-users='[{"name":"one","userName":"user_one"},
{"name":"two","userName":"user_two"},{"name":"three","userName":"user_three"}]'></div>
How can I load the list of users in the values?
const users = document.querySelector("#users");
const json = JSON.parse(users.dataset.users);
var tribute = new Tribute({
values: ** Load users this line **
});

I see that you are assigning the result of JSON.parse(users.dataset.users) to the constant "json". This leads me to think you may misunderstand the resulting value from JSON.parse.
The data-set value on the div is currently json, so document.querySelector("#users") will return the json value.
JSON.parse(users.dataset.users) will then convert the json (users.dataset.users) into a JavaScript value, in this case returning the array of users I believe you wish you assign to the values property in the Tribute constructor.
I've switched your variable names below to make this more clear.
const json = document.querySelector("#users");
const users = JSON.parse(json.dataset.users);
let tribute = new Tribute({ values: users });
* As "the_previ" pointed out, without the definition for Tribute it's unclear to us what value the "values" property expects (ie. String, Number, Array). I've assumed you're looking to pass in the array of users.

It's actually very simple using Lodash!
You just need to import Lodash, and use the map function:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
<script>
const users = document.querySelector("#users");
var json = JSON.parse(users.dataset.users);
const userlist = (_.map(json, "name"));
</script>
userlist will be an array containing every "name" value.
If you want to use userName values instead, just replace name with userName on the map function!

Related

json.dumps returns the objects as a string instead of a JSON object

In the views.py:
data1 = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(data1), cls=DjangoJSONEncoder).
I pass data as context to the html file.
In the HTML file, Using JS I access the JSON object with this code:
{{ data|json_script:"hello-data" }}
<script type="text/javascript">
var data = JSON.parse(document.getElementById('hello-data').textContent);
document.getElementById('id_line_one').onchange = function(event){
console.log(typeof data)
alert(data);
document.getElementById('id_line_one_unit_price').value = data[this.value];
};
</script>
I expect the var data to be a dictionary but it seems to be a String. Object.fromEntries is not working and I get the error Uncaught TypeError: Iterator value [ is not an entry object at Function.fromEntries (<anonymous>).
JSON.parse is removing the double quotation and I get [[1, 56000], [2, 55000]] but I am not able to access it as a dictionary. Whenever I use the index to access it, It returns the single characters as output instead of thinking of it as a dict object. How can I convert it into a dictionary? Thanks
The problem is that you are obtaining a list from the following line:
data1 = list(Inventory.objects.values_list('product_number','amount'))
Hence, you are just converting a list to JSON and, then, parsing this JSON, which yields a list.
Try to use the following instead:
from django.core.serializers.json import DjangoJSONEncoder
from django.core import serializers
data_obj_model = Inventory.objects.all()
data1=serializers.serialize('json', data_obj_model, cls=DjangoJSONEncoder)
Then, you can access, in your JavaScript code, all the fields of the model using data["fields"].field_of_interest.
Or you can also create a custom dictionary with the two fields you were interested in as follows:
data1 = dict(Inventory.objects.values_list('product_number','amount'))
This could be used as a dictionary in the JavaScript after parsing it.

Get object from Local Storage Angular 8

I have a localstorage which is storing some data. I am trying to get the data in a component using localStorage.getItem('id'); but it is undefined. The problem is, localStorage is storing id in a strange format. It is stored like abcabcabc.id Now there are multiple such parameters in localStorage and for each logged in user the string abcabcabc changes. How can I still get id value. Can I compare string or something to get values? Like if it contains string .id only read that value? If yes, can you explain how would that be achieved?
localstorage:
abcabcabc.username.id = sdfsdfsdfs
abcabcabc.username.refreshToken = sdfsdfs
abcabcabc.username.accessToken = ertsdffdg
Since you do not know the exact key stored in localStorage fetch all of them and then iterate over it. Next, match part of the key that you know i.e id as illustrated below:
// fetch all key-value pairs from local storage
const localStorageKeys = { ...localStorage };
// iterate over them
for (const index in localStorageKeys) {
// see if key contains id
if (index.includes('id')) {
// fetch value for corresponding key
console.log(localStorageKeys[index]);
}
}
localStorage sets data as a map of key-value pairs, so :
var id = {key:"id", value:"sdfsdfsdfs"}
//JSON.stringify converts the JavaScript object id into a string
localStorage.setItem('id', JSON.stringify(id));
now you get the data by:
var getTheId = localStorage.getItem('id');
//you can use JSON.parse() if you need to print it
console.log('getTheId: ', JSON.parse(getTheId));
This is how you would normally do it, but since I don't know how you had set the data, you would instead get the data by:
var x = localStorage.getItem(id);//normally getting your id
//parse it
var st = JSON.parse(x);
var ids = [];
while(st.includes(id)){
//this is to only get the abcabacabc
var newId = st.substring(0,9);
ids.push(newId);
}
console.log(ids);

How to update fields in Firestore map

Don't know how to go about adding new fields into a map in Firestore using a variable rather then a hardcoded field name.
I have a data structure in firestorm. The collection is called webQuiz and the document is called '12345. The data structure looks like:
roomName: Demo0
roomNumber: 46532
people:{11111:"David, 22222:"Peter}
Note that people is a map data object.
I would like to add another field to the people map. The code below works but instead of the data looking like
people:{11111:"David, 22222:"Peter, 44444:"Cathy"} it looks like
people:{11111:"David, 22222:"Peter, x:"Cathy"}
How can I use a variable which holds the field name in this situation? The x should be a variable but it is picked up literally as a property.
function testing(){
var x = "44444"
var y = "Cathy"
var cityRef = db.collection('webQuiz').doc('12345');
var setWithMerge = cityRef.set({
people: {x: y}
}, { merge: true });
I expect the output in firestorm to be
people:{11111:"David, 22222:"Peter, 44444:"Cathy"} but the actual output at the moment is
people:{11111:"David, 22222:"Peter, x:"Cathy"}
Thanks
You'll need to use the full field path as the key of the update:
var setWithMerge = cityRef.set({
`people.${x}`: y
});
This will prevent re-writing the entire "people" field, since you are specifying which property of the map to change directly.
Note that the field name and the property name are separated by a period.

Insert data in Firebase in Reactjs

During storing an object to my firebase, I am expecting the structure as image below, but what I get was a generated running number as a key. This is my code to store an object to firebase
var location = [];
location.push({
ms_jhr_1 : {
name: value
},
...
});
const a = firebase.database().ref('Food/'+id);
a.set(location);
How do I keep my structure without generate the running number?
The problem is you are using an array to store your data and then setting that array in firebase. To get the expected result you have to modify your code a little bit.
Here use this and remove other code
const a = firebase.database().ref('Food/'+id);
a.set(ms_jhr_1);
So you just need to pass the object you want to store under that id and not the whole array.
Note:- If you want to store multiple entries under one id then you have to push all those entries in an Object and not in array.
So it will look something like this
var location = {};
Now use for loop to insert all your data into this object (Remember, you are adding objects inside an object). You don't need array. Because in firebase data is stored in JSON tree format.
Hope it helps.

Saving more data to local storage

I know it is best way to use JSON but it is too complex for me to understand. Thus, may i ask is there any other ways to make sure that my data does not overwrite in local storage. Example using for loop or using another key name. Please help me by giving my examples as i am very new to HTML/JavaScript.
function saveToLS(){
var Name = document.getElementById("rName");
var namesaved = Name.value;
localStorage.setItem("Name",namesaved);
var Comment = document.getElementById("rComment");
var commentsaved = Comment.value;
localStorage.setItem("Comment",commentsaved);
}
Are you going to store multiples of these? You should store them in an array or object (for example adding a timestamp id field) and store that array in LS.
Yeah..Me Also new In this Part... but I hope to you help full this code please try It..
var key = 0;
for(key;key<10;key++){
localStorage.setItem(key, localStorage.getItem(key) + "Datas");
}
The best option is using JSON. JSON is not very complex. It's just a string which is a result of stringification of a language construct like an array or object.
What you need is an array: [], stringified version of it: "[]". So you need to push an element into the array. How? Convert the stored JSON string into an array by parsing it, and then push an element and stringify the new array. Here is an example:
var names = localStorage.getItem("Name");
names = names ? JSON.parse(names) : [];
names.push('newName');
localStorage.setItem("Name", JSON.stringify(names));
Also don't use 2 keys for storing 2 datum that belongs to one item. It will be hard to maintain. Use an object, an array of objects:
comments.push({
author: 'name of the author',
comment: 'here goes the comment body...'
})
function saveToLS(){
var Name = document.getElementById("rName");
var namesaved = Name.value;
if(localStorage.setItem("Name").length){ //the data already exists
// Do whatever if the data already Exists......
}else{
localStorage.setItem("Name",namesaved);
}
var Comment = document.getElementById("rComment");
var commentsaved = Comment.value;
if(localStorage.setItem("Comment").length){ //the data already exists
// Do whatever if the data already Exists......
}else{
localStorage.setItem("Comment",commentsaved);
}
}
check using localStorage.getItem(), if the data already exists and if its true don't write the data again or for that matter do whatever you want like save the data with another key
if(localStorage.setItem("Name").length){ //the data already exists
localStorage.setItem("SomethingElse...",namesaved); //something else
}else{
localStorage.setItem("Name",namesaved);
}

Categories