How to loop sql data into array and adding keys? [duplicate] - javascript

This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 5 years ago.
i would like to know how to loop all of my sql datas (that i parsed into a json table) into an array, with adding a key to each of them.
I know how i can loop all of the data into an simple string like this :
var dbString ="";
for(i = 0; i < result.response.length; i++)
{
dbString += result.response[i].names;
}
This would just look like this
var dbString = "James Michael Alfred....";
But how can i make this look like this :
var dbString = {"James":1, "Michael":2, "Alfred":3, .....}
Thanks.

It's a really unique demand to organise a list of names like you want, but here it is:
var dbString = {};
var names = result.response;
for(var i = 0; i < names.length; i++){
dbString[names[i]] = i + 1;
}

Related

Read through JSON number array using javascript loop [duplicate]

This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 5 years ago.
I`m trying to write a loop that will read through a nested number array.
The JSON file that I`m reading goes like this. each number key represents event dates.
json reference for startdate and end date
enter image description here
I have below javascript code that reads per var i = 1 or j = 1.
I`d like to read through entire nested number from dates and store them somewhere.
$(document).ready(function () {
$.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (data) {
var data = data;
var i = 2;
var obj = data[i].calEvent;
var bingname = obj.eventName;
var j = 1;
var startdate = obj.dates[j].startDateTime;
var time = new Date(startdate);
var starttime = time.getFullYear()+'-' + (time.getMonth()+1) + '-'+time.getDate();
var name = JSON.stringify(bingname);
document.getElementById("bingname").innerHTML = name;
document.getElementById("bingtime").innerHTML = starttime;
var name = firebase.database().ref("/bing").set({
EventName : name,
EventStart : starttime
});
});
});
Now, I should use something of incremental loop for var j. But I'm not sure how.
The problem for me is that json retrieved in obj.dates[j] doesn't seem like an array. I can't seem to read it as list of numbers to read through. Help is much appreciated.
If anyone can even sort this nearest to furthest from today's date that'd be Einstein:)
You will get an array of objects, that includes a callEvent object that has a dates property which is an array with objects with the property's startDateTime and endDateTime.
It will look like following:
[
{
callEvent: {
dates: [
{startDateTime: '', endDateTime: ''},
// more objects with start- and endDateTime
]
}
},
// more callEvent objects..
]
Now your code should loop through the array to get all callEvent objects and loop through all dates objects inside each callEvent.
$(document).ready(function () {
$.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (array) {
// loop through all elements in the array
for (var i = 0; i < array.length; i++) {
// loop through all dates inside the array
for (var j = 0; j < array[i].calEvent.dates.length; j++) {
console.log(array[i].callEvent.dates[j].startDateTime)
console.log(array[i].callEvent.dates[j].endDateTime)
}
}
});
});
Assuming the dates are valid JSON (JSON Validator), then you should just be able to get the data and loop through it:
for (var i=0;i<data.length;++i) {
console.log(data[i].startDateTime);
console.log(data[i].endDateTime);
}

Variable in a variable name? Looping said variables? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
So I have a chunk of code... and I want to make it more efficient by condensing it to a few lines instead of twelve. The idea I had was to use the variable of a loop to call each variable in sequence, since the code is just repeated with different numbers each time. Is there any way this could work?
var usetext1 = getText("text1");
var usetext2 = getText("text2");
var usetext3 = getText("text3");
var usetext4 = getText("text4");
var usetext5 = getText("text5");
var usetext6 = getText("text6");
usetext1 = usetext1.toUpperCase();
usetext2 = usetext2.toLowerCase();
usetext3 = usetext3.toLowerCase();
usetext4 = usetext4.toLowerCase();
usetext5 = usetext5.toLowerCase();
usetext6 = usetext6.toLowerCase();
Reduced to something like:
for (var i=2;i<6;i++){
var usetext[i]=getText("text[i]");
usetext[i]=usetext[i].toLowerCase();
You can use Template Literals to store the value into an array
var arr = [];
for (var i=1; i <= 6; i++){
arr.push(getText(`text${i}`).toLowerCase());
}

Acces a multidimensional array from database and save it

I have a 2D array that I get from a database. It looks like that:
arrayDB = [url1,name1,url2,name2,url3,name3, ...]
Now I want to save this array within my code. I tried:
function symbolsArray(syms){
var tableArray = [];
var tableArray2 = [];
for (var i = 0; i < syms.length; i++) {
tableArray[i] = syms[i][0]; //url
tableArray2[i] = syms[i][1]; //Name
}
}
However, this approach is not really suitable because I would need two return values. Is there maybe a better approach or a way to solve the content in a 2D array?
Syms is the data from the database.
Do take a look at
How can I create a two dimensional array in JavaScript?
that answers similar question about 2d arrays in javascript. Try something like-
function symbolsArray(syms){
var tableArray = [];
for (var i = 0; i < syms.length; i++) {
tableArray[i] = [syms[i][0] , syms[i][1]];
}
}
Your array is not two dimensional.You can seperate urls and names like this...
arrayDB = ['url1','name1','url2','name2','url3','name3'];//assumed array
urls = [];//array for urls
names = [];//array for names
for(i=0;i<arrayDB.length;i++){
(i%2==0)?urls.push(arrayDB[i]):names.push(arrayDB[i]);
}
console.log(names);
console.log(urls);
If ive got you right, your problem is that your code needs to return two things, but return does just one, right?
May Return an Object:
return {names: tableArray2,urls:tableArray};
You could use it like this:
var mydata=symbolsArray(arrayDB);
console.log(mydata.names,mydata.urls);
If you just want to deep clone, do:
var cloned=JSON.parse(JSON.stringify(arrayDB));
Or more elegantly:
var cloned=arrayDB.map(el=>el.map(e=>e));

Retrieving JSON Objects using javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Retrieve values from json encoded string
(3 answers)
Closed 9 years ago.
i have a problem in retrieving json objects. how to retrieve the objects inside the "choices" key object? thanks for your help...
Like so (to loop)
for (var i = 0; i < data.questions.length; i++) {
console.log(data.questions[i].choices.a);
console.log(data.questions[i].choices.b);
}
for (var i=0; i<questions.length; i++) {
var choices = questions[i].choices;
console.log(choices.a);
console.log(choices.b);
}
Assuming you have a var assigment like var myobj = { ... } where ... is your json object in the post, then you would access all the choices data points like this:
myobj.questions[0].choices.a
myobj.questions[0].choices.b
myobj.questions[1].choices.a
myobj.questions[1].choices.b
Are you asking something more specific about how to loop through all questions and choices?
Update: After your comment, I think you might be looking for something more like this:
for (var qi=0; qi < myobj.questions.length; qi++) {
var q = myobj.questions[qi];
console.log(q.ques);
for (var choiceKey in q.choices) {
console.log(" " + choiceKey + " --> " + q.choices[choiceKey]);
}
}
Simply replace the console.log() statements with whatever logic you need. The output of running the above code on your example JSON is this:
how old are you?
a --> 19
b --> 20
question two?
a --> answer1
b --> answer2

Need to concatenate strings from two arrays [duplicate]

This question already has answers here:
is the + operator less performant than StringBuffer.append()
(13 answers)
Closed 9 years ago.
I have two jQuery variables. Each variable is a text string containing words separated by a comma.
var myFirstVariable = green,blue
var mySecondVariable = circle,triangle
I would like to have a third variable retured like this:
var myThirdVariable = greencircle,bluecircle,greentriangle,bluetriangle
The order of the words in myThirdVariable is not important. But my first two variables can contain any number of words, so if
var myFirstVariable = green,blue,yellow
var mySecondVariable = circle,triangle,square
Then I need my third variable to returned like this:
var myThirdVariable = greencircle,bluecircle,yellowcircle,greentriangle,bluetriangle,yellowtriangle,greensquare,bluesquare,yellowsquare
I think I need to push() both variables into an array but I'm struggling with this area of jQuery. Hope someone can shed some light on this. Many thanks.
I'm struggling with this area of jQuery
That's simply because the jQuery library has no tools for this kind of work.
Use the native JavaScript functionality instead, specifically the String split method, the Array join method, the string concatenation operator + and for-loops:
var myFirstVariable = "green,blue"
var mySecondVariable = "circle,triangle";
var firstArr = myFirstVariable.split(","),
secondArr = mySecondVariable.split(","),
thirdArr = [];
for (var i=0; i<firstArr.length; i++)
for (var j=0; j<secondArr.length; j++)
thirdArr.push(firstArr[i]+secondArr[j]);
var myThirdVariable = thirdArr.join(",");
You can use the plain old string split method to get 2 arrays.
http://www.w3schools.com/jsref/jsref_split.asp
You could then use nested for loops to push the new strings into your 3rd array and then use the join method to create the final string.
http://www.w3schools.com/jsref/jsref_join.asp
Try
var myFirstVariable = 'green,blue'
var mySecondVariable = 'circle,triangle'
var myThirdVariable = fn(myFirstVariable, mySecondVariable);
console.log(myThirdVariable)
function fn(fv, sv){
var fa = fv.split(','), sa = sv.split(','), ta = [];
for(var i = 0; i < fa.length; i++){
for(var j = 0; j < sa.length; j++){
ta.push(fa[i] + sa[j])
}
}
return ta.join(',')
}
Demo: Fiddle
OK so you don't need jquery to achieve this, just JavaScript.
check out this answer here to help you:
How to merge two arrays in Javascript and de-duplicate items

Categories