I have to take each data of the array inside an array but it doesn't work when I use something like tmp.name or tmp[0].name would result undefined and even tmp.length result 0
var tmp = [];
var db = firebase.firestore();
var docCollection = db.collection('doctors');
var assignedDoctors = docCollection.where('assign', '==', user.key).get();
assignedDoctors.then(function(doc){
let i = 0;
doc.forEach(function(md){
tmp.push(md.data());
tmp[i].key = md.id;
i++;
});
}).catch(function(e){
console.log(e);
});
console.log(tmp)
the tmp result
[]
0: {assign: "userA", name: "NameA"}
1: {assign: "userA", name: "NameB"}
length: 2
__proto_: Array(0)
Just declare map and assign all data of md.data() to map and then push map into array and remove variable i as no need of it. Like following:
doc.forEach(function(md){
var map = {};
map = md.data();
map.key = md.id;
tmp.push(map);
});
var tmp = [];
var db = firebase.firestore();
var docCollection = db.collection('doctors');
var assignedDoctors = docCollection.where('assign', '==', user.key).get();
assignedDoctors.then(function(doc){
let i = 0;
doc.forEach(function(md){
tmp.push(md.data());
// tmp[i].key = md.id;
// i++;
});
}).catch(function(e){
console.log(e);
});
console.log(tmp)
comment these line and check it.
Related
So right now this is my current code and I'm trying to figure out a way to loop through the variables I've already declared (Assuming variables 1-9 already have values). I just wanted to know whether this was possible at all?
var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
var whyTitles = [];
var whyDescs = [];
var funTitles = [];
var funDescs = [];
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
Output I want if we printed out the looped code:
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
var obj = {'briefs' : brief};
if(localStorage.getItem('briefs') != null) {
var tmp1 = JSON.parse(localStorage.getItem('briefs'));
for(var i = 0;i<tmp.length;i++) {
briefs.push(tmp[i]);
}
}
briefs.push(obj);
localStorage.setItem("briefs", JSON.stringify(briefs));
var obj = {'hovers' : hover};
if(localStorage.getItem('hovers') != null) {
var tmp2 = JSON.parse(localStorage.getItem('hovers'));
for(var i = 0;i<tmp.length;i++) {
hovers.push(tmp[i]);
}
}
hovers.push(obj);
localStorage.setItem("hovers", JSON.stringify(hovers));
...etc
If the code is running in a browser, then you can do something like:
for(key in window) { console.log(window[key]) } // print all variables
The variables are associated to the global namespace. That is to say the upmost "this" reference or the window object.
You're almost there with the code you have. If you look at your "desired output" examples, you'll see that the only thing that really differs between each element of your "unrolled loop" is the key for local storage ('titles', 'briefs', 'hovers').
With that in mind, you could use an Object to map the keys to the variables you have at the top level. So this:
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
...
Becomes (UPDATE: with the initializer values preserved):
var key_to_collection = {
'titles': [title],
'briefs': [brief],
'hovers': [hovers],
'whatTitles': [whatTitles],
'whatDescs': [whatDescs],
}
Then, you loop over the values of this object:
Object.keys(key_to_collection).forEach(function(key) {
var obj = {};
collection = key_to_collection[key];
obj[key] = collection;
if(localStorage.getItem(key) != null) {
var tmp = JSON.parse(localStorage.getItem(key));
for(var i = 0;i<tmp.length;i++) {
collection.push(tmp[i]);
}
}
collection.push(obj);
localStorage.setItem(key, JSON.stringify(collection));
});
If your variable name is title for example, then you can access it using window['title']. This means that if you define an array of your global variable names:
const varNames = ['title', 'brief', 'hover', ...]
Then you can do a loop like the following
for(const name of varNames) {
const value = window[name]
// do whatever you want using the variable name and value
}
I hope this solves your issue :)
I have a HTML Site with 4 inputRange slidern. If a user click on a button all the values from the ranges should be stored in a nested JSON Object. So far so good, but JS only saves the last one in that Array and not the others before.
But all Sliders have different values from 1 to 5, but JS saves only the 4 from the last slider. Here's my code:
//Speichert die aktuellen Angaben in einem Nested-JSON Objekt
function saveBewertung() {
var jsonObj = {};
var kriterien = [];
var bewertungen = {};
//Loop
$('input[type=range]').each(function() {
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id;
bewertungen.note = note;
kriterien.push(bewertungen);
jsonObj.Bewertungen = kriterien;
});
jsonObj.Kommentar = $('textarea#kommentar').val();
//TEST AUSGABE
alert(JSON.stringify(jsonObj));
}
Result:
You are pushing the same object to the array again and again. You need to initialize bewertungen every time in the each block.
Declare
var bewertungen = {};
inside the each block
$('input[type=range]').each(function() {
var bewertungen = {};
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id;
bewertungen.note = note;
kriterien.push(bewertungen);
});
jsonObj.Bewertungen = kriterien; //this line can be moved out
Another possibility next to the solution from #gurvinder372 is to shorten the function so you don't need to declare the variables bewertungen, id and note:
//Speichert die aktuellen Angaben in einem Nested-JSON Objekt
function saveBewertung() {
var jsonObj = {};
var kriterien = [];
//Loop
$('input[type=range]').each(function() {
// Anonymous object
kriterien.push({
id: $(this).attr("id"),
note: $(this).val()
});
});
jsonObj.Bewertungen = kriterien;
jsonObj.Kommentar = $('textarea#kommentar').val();
//TEST AUSGABE
alert(JSON.stringify(jsonObj));
}
Here is some description how this thing is working
var bewertungen = {}; // this line declare the object this object will hold values in each loop.
$('input[type=range]').each(function() {
var bewertungen = {};
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id; // this line add value to {bewertungen} object key
bewertungen.note = note; // this line add value to {bewertungen} object key
kriterien.push(bewertungen); // every itration will push value to [kriterien] array
});
jsonObj.Bewertungen = kriterien; // this is final array with all values
I have these following arrays
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1','platform-a2','platform-a3'];
var platform_b = ['platform-b1','platform-b2','platform-b3'];
var platform_c = ['platform-c1','platform-c2','platform-c3'];
And I want to convert them into a json which should look like this
{
"Guitar":["platform-a1","platform-a2","platform-a3"],
"Bass":["platform-b1","platform-b2","platform-b3"],
"Amp":["platform-c1","platform-c2","platform-c3"]
}
How would I do this? I would have to do this in pure javascript
Let's present three different approaches to your case:
First one
If you want just to create the json object with your data try:
http://jsfiddle.net/csdtesting/tap2xom9/
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var category = ['Guitar', 'Bass', 'Amps'];
var obj = {
Guitar: platform_a,
Bass: platform_b,
Amps: platform_c
};
document.write(JSON.stringify(obj));
Second
If you want to create it dynamically do something like that:
http://jsfiddle.net/csdtesting/tap2xom9/
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var FinalObject = {};
FinalObject[category[0]] = platform_a;
FinalObject[category[1]] = platform_b;
FinalObject[category[2]] = platform_c;
document.write(JSON.stringify(FinalObject));
Finally
If you want to be more dynamic then try this :
http://jsfiddle.net/csdtesting/kqwz72os/
var FinalObject = {};
var category = ['Guitar', 'Bass', 'Amps'];
var platforms = {
platform_a: ['platform-a1', 'platform-a2', 'platform-a3'],
platform_b: ['platform-b1', 'platform-b2', 'platform-b3'],
platform_c: ['platform-c1', 'platform-c2', 'platform-c3']
};
for (var i = 0; i < category.length; i++) {
FinalObject[category[i]] = platforms[Object.keys(platforms)[i]];
}
document.write(JSON.stringify(FinalObject));
Hope this helps!
There's no reasonable shortcut here. You just have to do it manually:
var jsonString = JSON.stringify({
"Guitar": platform_a,
"Base": platform_b,
"Amp": platform_c
});
function myFunction() {
var item = {};
item = {id:'myId', rules: {1:'rule1', 2:'rule2'}};
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // rule1
var db = ScriptDb.getMyDb();
db.save(item);
var result = db.query({id:'myId'});
item = result.next();
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // undefined, why?
}
Expecting the last log to return the value "rule1" like in the original object.
Why is it now undefined?
A strange case, it may be a bug.
With the following code can get what you need:
...
item = JSON.parse(item.toJson());
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // rule1
...
An alternative route for storing and filtering results with a numerical value instead of with a numerical key.
function myFunction() {
var db = ScriptDb.getMyDb();
var item1 = {id:'myId', rule:{num:1, details:'rule1'}};
var item2 = {id:'myId', rule:{num:2, details:'rule2'}};
var saveResults = db.saveBatch([item1, item2], false);
var results = db.query({id:'myId'});
while (results.hasNext()) {
var item = results.next();
if (item.rule.num == 1)
Logger.log(item.rule.details); // rule1
}
}
I want to sort results obtained from indexedDB.
Each record has structure {id, text, date} where 'id' is the keyPath.
I want to sort the results by date.
My current code is as below:
var trans = db.transaction(['msgs'], IDBTransaction.READ);
var store = trans.objectStore('msgs');
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound("");
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false){
return;
}
console.log(result.value);
result.continue();
};
Actually you have to index the date field in the msgs objectStore and open an index cursor on the objectStore.
var cursorRequest = store.index('date').openCursor(null, 'next'); // or prev
This will get the sorted result. That is how indexes are supposed to be used.
Here's the more efficient way suggested by Josh.
Supposing you created an index on "date":
// Use the literal "readonly" instead of IDBTransaction.READ, which is deprecated:
var trans = db.transaction(['msgs'], "readonly");
var store = trans.objectStore('msgs');
var index = store.index('date');
// Get everything in the store:
var cursorRequest = index.openCursor();
// It's the same as:
// var cursorRequest = index.openCursor(null, "next");
// Or, if you want a "descendent ordering":
// var cursorRequest = index.openCursor(null, "prev");
// Note that there's no need to define a key range if you want all the objects
var res = new Array();
cursorRequest.onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) {
res.push(cursor.value);
cursor.continue();
}
else {
//print res etc....
}
};
More on cursor direction here: http://www.w3.org/TR/IndexedDB/#cursor-concept
IDBIndex API is here: http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex
Thanks to zomg, hughfdjackson of javascript irc, I sorted the final array. Modified code as below:
var trans = db.transaction(['msgs'], IDBTransaction.READ);
var store = trans.objectStore('msgs');
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound("");
var cursorRequest = store.openCursor(keyRange);
var res = new Array();
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false){
**res.sort(function(a,b){return Number(a.date) - Number(b.date);});**
//print res etc....
return;
}
res.push(result.value);
result.continue();
};