Retrieving JSON Objects using javascript [duplicate] - javascript

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

Related

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

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;
}

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);
}

How to retrieve value in URL and store it in variable [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 7 years ago.
I have an url like below
http://www.grcparfum.it/home.php?section=letteradelpresidente&lang=eng
in this URL language is english
lang=eng
i wanna call different JS file when lang is different
Here's a function that can get the querystring variables in JS for you:
function $_GET(q){
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1){
var query = document.location
.toString()
.replace(/^.*?\?/, '')//Get the query string
.replace(/#.*$/, '')//and remove any existing hash string
.split('&');
for(var i=0, l=query.length; i<l; i++){
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
return $_GET[q];
}
Does this help at all?

Dynamic array names in jQuery [duplicate]

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 9 years ago.
I have an array that holds several values. I have several other areas, each with a different number instead of the
var u3s0A = ["Ques De Ti", "Encina", "Renaissance", "Syllabic", "Polyphonic", "None"];
However, I was unable to figure out how to refer to the arrays dynamically. I tried doing:
alert(u3s + randomNumber + A[p]);
but only got errors. I realize that if i do
alert('u3s' + randomNumber + 'A'[p]);
it outputs the correct array name, but it is then transformed to a string and when I index it:
var arrayHolder = 'u3s' + randomNumber + 'A';
alert(arrayHolder[0]);
I get the first number in the array name (u), not the first item in the array.
Any help would be appreciated!
Thanks so much for your time.
Try this way, creating a temporary object and set the arrays as properties of the object and then access it using the bracket notation with the constructed property name:
var ob = {};
ob.u3s0A = ["Ques De Ti", "Encina", "Renaissance", "Syllabic", "Polyphonic", "None"];
ob.u3s1A = ["Ques De Ti", "Encina", "Renaissance", "Syllabic", "Polyphonic", "None"];
.....
and then
alert(ob['u3s' + randomNumber + 'A'][p]);
If this is in global scope and if you are in browser you can access it with window object with the same way as above instead of the temp object ob.
Demo
Try something like this:
window['u3s' + randomNumber + A[p]]

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