Display JSON arrays in innerHTML - javascript

so I received the following array from another student and my job is to display it in the HTML.
I've followed examples found on here as well as other sites. It's my first attempt at doing this.
Anyway, I've called in the required values, but they're not displaying. I'd appreciate any help I can get.
This is the script block and I'll attach some of the HTML. Currently the json is situated before the closing head tag.
<script>
var height = {"height" : "1.76m"};
var weight = {"weight" : "65kg"};
var bmi = {weight/(height*height)};
var cholesterol = {"cholesterol" : "26mmol/d"};
var glucose ={"glucose" : "100mg/dl"};
var pressure = {"pressure" : "120/80"};
var pulseRate = {"pulse rate" : "80bpm"};
window.onload = function() {
obj = JSON.parse(height, weight, bmi, cholesterol, glucose, pressure, pulseRate);
document.getElementById("hgt").innerHTML = obj.height[1];
document.getElementById("wgt").innerHTML = obj.weight[1];
document.getElementById("bmi").innerHTML = obj.bmi[1];
document.getElementById("chol").innerHTML = obj.cholesterol[1];
document.getElementById("gluc").innerHTML = obj.glucose[1];
document.getElementById("bp").innerHTML = obj.pressure[1];
document.getElementById("rpr").innerHTML = obj.pulseRate[1];
};
</script>
<div class="col-xs-2">
<h3 class="heading">Today</h3>
<img class="picture2" src="images/icon-height.png" />
<div class="caption">
<h2 id="hgt"></h2>
<p>height</p>
</div>

Since your variables height, weight... do not have to be parsed, since they are valid JSON Objects, you could save yourself some time by assigning obj like this:
var obj = {
height: "1.76",
weight: "65kg",
...,
bmi: //your calculation here!
};
document.getElementById("yourid").innerHTML = obj.weight;
...
Since JSON objects use key:value pairs, you can simply access the values by using object.key or object['key'].
Since you're trying to access the values by using obj.weight[1] I'm guessing that you're trying to get the second value in { "weight" : "67kg" }. But since this is a valid Object, weight is the key and "67kg" is the value. So you are trying to get the value at index 1 on an Object (obj.weight[1]). For this to work your object must have a key 1 or be an array. I hope you get what I'm trying to explain to you.
To make it a lot more simpler, you could just use height.height instead of the not working obj.height[1], because your var height is an object with a key height. But for readability I would suggest the format from my snippet.

Related

How can I concatenate two strings into a variable name with Javascript or jQuery?

This question has been asked before, I wanted to create a (possibly) simpler version for others to (maybe) understand easier.
What I wanted to do was combine a string with the data (string) from a variable to create a variable name. I suppose it would be called a dynamic variable?
In this example I want to add a class and text to a div..
<div class="time fa"></div>
..based on changing data which I get from a json file.
var timetain = 10;
var timebus = 20;
var icontrain = 'fa-train';
var iconbus = 'fa-bus';
var type = 'bus'; // this string comes from a json file, it will either be train or bus
So I want to add the word time to the data from the variable named type to output the data from either timetrain or timebus
$('.time').text('Travel by bus will take |'time'|+|type| minutes');
$('.time').addClass(|'icon'|+|type|));
I suppose another way of wording the question would be "How to combine a variable's data with a string to get the data from a third variable with Javascript?"
Using ES6 template literals:
var time = "30",
typesArr = ["bus", "train", "foot"],
type = typesArr[ Math.random()*typesArr.length|0 ]; // pick random array item
// mix values with strings:
document.write( `Travel by ${type} will take ${time} minutes` );
Basically you cannot construct a variable name in javascript, unless it is an Object's Key, so you have to store the keys in some object in order to access them, but in your case it's much easier:
$('.time').addClass('icon fa-' + type); // example => 'icon fa-train'
But if you really wanted to construct the keys dynamically you could do:
var types = {
train : "fa-train",
bus : "fa-bus"
};
var whatever = "bus";
var type = types[whatever]; // "fa-bus"
Why not make an associative array of the times?
time = {'bus': 20, 'train': 10}
etc.? Than just access it with time[type]. This is much safer than what you want to do (you would have to rely on eval), which seems like overkill for this.
Nicht so #Hastig, lieber ordentlich machen.
A better solution without using Eval:
Most programming languages nowadays support a data-structure to "group" variables that belong together. It's called an Object. I can't come up with a single disadvantage in using Objects over multiple variables.
This approach is even (a teeny tiny bit) faster than your attempt with eval().
var configByType = {
"train": {
label: "train",
time: 10,
icon: "fa-train"
},
"bus": {
label: "bus",
time: 20,
icon: "fa-bus"
}
}
function travel(type){
//because creating and adding a new `span` is simpler
//than checking wich classes to remove on `.time.fa`
var $span = $('.time').html('<span>').children();
if(type in configByType){
let config = configByType[type];
$span.addClass(config.icon)
.text('Travel by '+ config.label +' will take ' + config.time + ' minutes')
}else{
$span.text('unsupported type: ' + type);
}
}
$('#update').click(function(){
var types = ["car", "bus", "train", "plane"];
var randomType = types[Math.floor(Math.random() * types.length)];
travel(randomType)
});
travel('bus');
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="time fa"></div>
<br>
<input id="update" type="button" value="update" />
A Solution Using Eval
eval('string' + variableName)
Applied To Provided Code
var timetain = 10;
var timebus = 20;
var icontrain = 'fa-train';
var iconbus = 'fa-bus';
var type = 'bus'; // this data (string) comes from a json file, it will either be train or bus
$('.time').text('Travel by bus will take ' + eval('time' + type) + ' minutes');
$('.time').addClass(eval('icon' + type));
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="time fa"></div>
Note
Before using this solution be sure to read more about the criticisms of using eval
This solution works and addresses the question as asked. I assume the downvotes are because of the criticisms that I pointed out and that there are better ways to go about things if properly planned but we'll never know because nobody cared to explain themselves.
I needed the simple eval way because I was putting together a complicated web of different json file comparisons for a simple game app and needed a quick and easy 'variable-variable', php-style method as placeholder code until I was able to better think everything through.
In the more advanced versions I am using objects and arrays like recommended in the other answers here but I was unable to think through things without using eval as temporary 'scaffolding'.
Fiddle
https://jsfiddle.net/Hastig/o169ja8w/

setting object through variable containing strings not working

I have developed a pretty basic audio player on on my website similar to SoundClouds.
I have managed to successfully finish it, and I am starting to clean up all the markup, including (trying) removing all inline event handlers (i.e: onclick="" or onkeyup="").
However, I have come across a bit of a problem in my JavaScript whilst doing this.
It's a bit hard to explain so I'm going to post my JavaScript, then give you an idea of what the problem is:
$(".track-w__trigger").click(function(){
var tid = $(this).attr('aria-trackid'); // aria-trackid is equal to a random integer created by PHP
var tiW = 'w' + tid + 'w'; // this is an object (i.e: w3w)
playPauseButton(this, tiW, ti);
});
function playPauseButton(button, wave, trackID){
var button = $(button);
if(wave.isPlaying()){ // the object (w3w.isPlaying())
button.removeClass("playing");
wave.pause();
} else {
button.addClass("playing");
wave.play();
}
}
What I used to have was
<div class="track-w__trigger" onclick="playPauseButton(this, w3w, 3)" id="w3w-trigger"></div>
and now it is:
<div class="track-w__trigger" aria-trackid="3" id="w3w-trigger"></div>
As you can see in the second block of code. w3w is an object. However, because I have set it using my click function in a separate script using string quotes. JavaScript has gone ahead and made it a string.
So now when I use wave.isPlaying() for example; it does nothing.
I have no idea how to fix this, and no result on Google will help me. Any help in fixing this issue would be greatly appreciated,
Thanks!
EDIT:
This is where & how w3w is set:
var w3w = Uki.start({
// e.t.c
});
Use eval
wave = eval(wave);
to evaluate the string as a function
or use a safer way
wave = window[wave];
https://jsfiddle.net/zmr412q7/
Instead of having each object as a seperate variable, create an object that contains each object at the id representing the N in wNw. Ex:
var wNw = {};
// represents w1w
wNw[1] = (Uki.start({
// e.t.c
}));
// represents w17w
wNw[17] = (Uki.start({
// e.t.c
}));
// represents w3w
wNw[3] = (Uki.start({
// e.t.c
}));
This gives you an object that looks like:
{
1: object_that_was_w1w
17: object_that_was_w17w
3: object_that_was_w13w
}
And then your click handler looks like this:
$(".track-w__trigger").click(function(){
var tid = $(this).attr('aria-trackid'); // aria-trackid is equal to an integer of 1 to 5
var tidNum = parseInt(tid);
playPauseButton(this, wNw[tidNum], ti);
});
You can try something like this,
var tid='w'+5+'w';
var tryout=tid.valueOf();
console.log("getting the object "+tryout)
The valueOf property converts the string to an object

How would I go about using a multidimensional array variable in javascript

Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.

JavaScript: Access object variable inside nested array

How would I access ArrayObjectVariable inside
ArrayObject[0]? I know if you don't have a [ ] around it its as simple
as ArrayObject[0].ArrayObjectVariable?
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{ ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0]???);
I didn't realize the whole "ArrayObject[0][0].ArrayObjectVariable" thing. Thanks for the replies. I was trying it with just one ("[0]") instead of two ("[0][0]"). My second question is, what is the second "[0]" for? I just tried making multiple variables and it still used "[0][0]" ? So what's the second "[0]" controlling?
Third question? I noticed that it created a variable outside the array when I did that? When I change the value of the variable in the array, it has no effect on the one outside of it? Likewise, when I change the value of the variable outside of the array it has no effect on the one inside it. Is there a way to create the array without creating a variable outside of the array with the same name? Thanks :)
OK figured it out :) Just make the Object in the array without the "[ ]". The whole point of this was to figure out how to access nested items but I got it now. Didn't realize how to make them without the "[ ]". Example for those of you struggling like I was:
// create variables that we are going to use in Array Objects. Or make a function with the values.
var ATV1 = 'AyTeeVeeOne', ATV2 = 'AyTeeVeeTwo', ANV1 = 'AyEnVeeOne';
var ATV3 = 'AyTeeVeeThree', ATV4 = 'AyTeeVeeFour', ANV2 = 'AyEnVeeTwo';
// Make an Array
var ArrayObject;
ArrayObject = [{}];
// Insert variables into Array object(s).
ArrayObject[0] = {ArrayTestObject1 : { ArrayTestValue1:ATV1,
ArrayNestedObject1:{ ArrayNestedValue1:ANV1 },
ArrayTestValue2:ATV2
}};
ArrayObject[1] = {ArrayTestObject2 : { ArrayTestValue3:ATV3,
ArrayNestedObject2:{ ArrayNestedValue2:ANV2 },
ArrayTestValue4:ATV4
}};
// Access Array Object Variables
alert(ArrayObject[0].ArrayTestObject1.ArrayTestValue1) // Example 1
alert(ArrayObject[1].ArrayTestObject2.ArrayNestedObject2.ArrayNestedValue2) // Example 2
ArrayObject[0][0].ArrayObjectVariable
You have an array for the value of ArrayObject[0], so treat it like any other array.
use this:here you have ArrayObject as array and you are creating index as zero to the array and in that on zeroth place ArrayObjectVariable key resides.
<script>
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{
ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0][0].ArrayObjectVariable);
</script>

Read Json Variable

{"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]}
How do i write the code to read the teamid and teamname so as to store them in seperate variables?
Please Help!
If it is a JSON string, parse it...
var obj = jQuery.parseJSON(jsonString);
Then work with the information
obj.TeamList[0].teamid;
obj.TeamList[0].teamname;
TeamList is an array so if you have more than one "team" you'll need to loop over them.
You have an object containing an array TeamList, which has one object as its elements:
var tl = {"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]};
var id = tl.TeamList[0].teamid;
var name = tl.TeamList[0].teamname;
If the example you have posted in contained as a string you can parse it like so with javascript...
var jsonObject = JSON.parse(myJsonString);
you can then access your array like so...
jsonObject.TeamList
and each item in TeamList...
jsonObject.TeamList[i].teamid
jsonObject.TeamList[i].teamname
finally assuming you have one item in TeamList and making an attemp to directly answers you question...
var teamid = jsonObject.TeamList[0].teamid;
var teamname = jsonObject.TeamList[0].teamname;
hope that makes sense
in which language? Basically after parsing using json you would do something like this on the result:
result["TeamList"][0]["teamname"] to get teamname and result["TeamList"][0]["teamid"] to get teamid.
If you can use json_decode, like this :
$content = '{"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]}';
$json = json_decode($content);
$obj = $json->{'TeamList'}[0];
print $obj->{'teamid'}."//".$obj->{'teamname'};
You had tagged your question as jQuery? We're you wanting to display this information on a page?
Given some sample html:
<label>Team ID:</label>
<div id="teamid"></div>
<label>Team Name:</label>
<div id="teamname"></div>
And a little jquery:
var obj = {"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]};
$('#teamid').html(obj.TeamList[0].teamid);
$('#teamname').html(obj.TeamList[0].teamname);
Would allow you to accomplish this. As others have pointed out you would need to iterate over the collection if there were multiple teams.

Categories