Insert Object data in HTML [duplicate] - javascript

This question already has answers here:
How to loop through a plain JavaScript object with the objects as members
(28 answers)
Closed 8 years ago.
How can I list the structured contents of a Javascript Object in HTML?
My object looks like this:
var lists = {
"Cars":{"Ford":false,"Ferarri":false},
"Names":{"John":true,"Harry":false},
"Homework":{"Maths":true,"Science":false,"History":true,"English":true}
}
What would the loop look like to print the keys as headers, and the property + values as an ordered list underneath?
Example:
Cars
Ford = False
Ferrari = False
Names
John = True
Harry = False
Homework
Maths = True
Science = False
History = True
English = True
I understand that I can append the object by name to HTML, but if the object is dynamic, and the key isn't known, how can I make a loop to do so?

Just got to loop, create the HTML string, and append! Say you have a container:
<div id="container"></div>
And your JS
var htmlString = "";
for (var key in lists) {
htmlString += "<span>" + key + "</span>";
htmlString += "<ul>";
for (var item in lists[key]) {
htmlString += "<li>" + item + " = " + lists[key][item] + "</li>";
}
htmlString += "</ul>";
}
document.getElementById("container").innerHTML = htmlString;
Working demo: http://jsfiddle.net/owqt5obp/

Related

JSON.parse() returning strings

I am trying to iterate through an array of objects and populate an HTML select element with options whose values are the entire contents of each object. The population is successful, but the objects are turned into strings in the process and I do not know how to turn them back into objects.
Running them through JSON.parse() gives me "Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse." My research suggests that this happens when you use JSON.parse() on something that is already an object, but running typeOf() on the data beforehand reveals that it is a string.
I do not get this error if I instead run the data through JSON.parse(JSON.stringify(data)), but its output remains a string.
Please help me understand what I am misapprehending about JSON.parse(). Thank you.
const selectors = document.getElementsByClassName("ingredientSelector");
const cookButton = document.getElementById("cookButton");
//very large array of ingredient objects
let selectorOptions = "<option value = 'Nothing'>Nothing</option>";
for (let i = 0; i < ingredients.length; i++){
selectorOptions += ("<option value = '" + ingredients[i] + "'>" + ingredients[i].name + "</option>");
}
Array.prototype.forEach.call(selectors,function(selector){
selector.innerHTML = selectorOptions;
});
function cook(ingredients){
console.log("Cooking with ingredients: " + ingredients);
}
cookButton.addEventListener("click", function(){
let ingredients = [];
Array.prototype.forEach.call(selectors,function(selector){
if(selector.value !== 'Nothing'){
console.log(typeof(selector.value))
JSON.parse(selector.value);
let JSONString = JSON.stringify(selector.value);
console.log(typeof(JSONString));
let JSONObject = (JSON.parse(JSONString));
console.log(typeof(JSONObject));
console.log(JSONObject.name);
}
console.log(ingredients);
cook(ingredients);
});
});
The issue is how you're building the value properties for the options you're inserting into each selector. On this line:
selectorOptions += ("<option value = '" + ingredients[i] + "'>" + ingredients[i].name + "</option>");
Your comment says that ingredients is an array of objects, so ingredients[i] will be an object. Concatenating an object to a string will, by default, turn it into [object Object] - and this is what's causing your error. You're ending up with an option that looks something like this, perhaps:
<option value = '[object Object]'>Raw Prime Meat<object>
There's two perfectly valid approaches here. You can either store the ingredient index in the option values, which you can then use to lookup the ingredient from your master array later, or you should use JSON.stringify(ingredients[i]) to turn the object into a JSON.parseable string to make your code work as-is.
So this would work fine:
selectorOptions += ("<option value = '" + JSON.stringify(ingredients[i]) + "'>" + ingredients[i].name + "</option>");

Get Length of nested JavaScript object

I want to fill a list with elements from a database. The data comes from a PHP file in JSON format. The JSON looks like this:
{"Venues" : [{"name":"McManus Galleries","id":"1"},{"name":"Dundee Law","id":"2"},{"name":"University of Abertay","id":"3"},{"name":"Baxter Park","id":"4"},{"name":"Overgate Shopping Centre","id":"5"}]}
Now I am handling this text with the following code:
obj = JSON.parse(this.responseText);
document.getElementById("list").innerHTML = "<a onclick='getVenue("+obj.Venues[0].id + ")'>" + obj.Venues[0].name + "</a><br>";
document.getElementById("list").innerHTML += "<a onclick='getVenue("+obj.Venues[1].id + ")'>" + obj.Venues[1].name + "</a><br>";
...and it works, but now I want to do it with a for-loop so no matter how many items "Venues" contains it is showing them all in the list. I got this code right now:
for(i = 0; i < obj.length; i++){
document.getElementById("list").innerHTML += obj.Venues[i].name;
}
The problem here is, that obj.length returns 1. Does anybody know how to solve this?
obj is the main object that has child Venues (that is an array to be used for iteration as below)
for(i = 0; i < obj.Venues.length; i++){
document.getElementById("list").innerHTML += obj.Venues[i].name;
}

Display JavaScript array in vertical list

I have an array I have generated and I want to display it in html as a vertical list, preferably as each individual element.
I have done this:
var a = _.intersection(viewedUserLikedUsersArray, loggedInLikedUsersArray);
for (var i=0; i < a.length; i++){
displayListOfMatches.innerHTML = a[i];
}
but obviously this way will replace the innerHTML with the last element in the array rather than stacking each one on top of each other
You'll probably get people saying to do this:
displayListOfMatches.innerHTML = "<p>" + a.join("</p><p>") + "</p>";
...which works but note that the content of the array entries will be parsed as HTML.
If that's not okay, you can either build an HTML string by replacing those characters via map:
displayListOfMatches.innerHTML = a.map(function(entry) {
return "<p>" + entry.replace(/&/g, "&").replace(/</g, "<") + "</p>";
}).join("");
...or build the elements as you go, perhaps with forEach:
displayListOfMatches.innerHTML = ""; // You can leave this out if it's empty
a.forEach(function(entry) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(entry));
displayListOfMatches.appendChild(p);
});
Of course, in all cases, you can adjust it to use different elements/markup.

Javascript getting object properties

I want to create a google.Visualization.DataTablein the end, to show a graph. By now, I have a Problem with the following:
This is my code for getting Object from JSON-string and listing Properties:
var jsonData = <?php echo "'". $jsonTable. "'"; ?>;
var parsed = JSON.parse(jsonData);
var sensors = [];
for (var x in parsed){
sensors.push(parsed[x]);
}
var text ="";
for (var sensor in sensors){
if (sensors.hasOwnProperty(sensor)){
var measures = sensors[sensor];
text += ('\r\n' + sensor);
for (var time in measures){
if(measures.hasOwnProperty(time)){
text += ('\r\n' + time + " = " + measures[time]);
}
}
}
}
$(document.getElementById('chart_div')).text(text);
And my jsonData looks like this:
jsonData = '{"sensor1":
{"Date(2016,1,08,10,30,03)":19.187,
"Date(2016,1,08,10,00,02)":18.937[,...]},
"sensor2":
{"Date(2016,1,08,10,30,04)":18.687,
"Date(2016,1,08,10,00,03)":18.437[,...]}
[,...]}'
My Problem is that i don't get the values "sensor1", "sensor2" and so on in the loop. text += ('\r\n' + sensor); only returns the index of the sensor-object in the sensors-object.
How can I get the sensor name instead of the index?
One simple workaround
Remove the var sensors = [];
Find sensors and replace with parsed.
Code:
for (var sensor in parsed){
if (parsed.hasOwnProperty(sensor)){
var measures = parsed[sensor];
text += ('\r\n' + sensor);
console.log(parsed);
for (var time in measures){
if(measures.hasOwnProperty(time)){
text += ('\r\n' + time + " = " + measures[time]);
}
}
}
How can I get the sensor name instead of the index?
You need to do something with the property name in your first loop.
At present you are taking the property name (sensor1), using it to get the value ({"Date...) and then putting the value in an array while discarding the property name.
The simplest option would be to get rid of your first loop entirely and work with parsed instead of sensors in your second loop.

JSON location storing in Javascript [duplicate]

This question already has answers here:
JSON dot notation to string
(3 answers)
Closed 9 years ago.
I am converting JSON data into a list structure, and I want to save the "AAA.BBB[0].CCC.DDD[5].EEE" format as the id so when a user modifies the content of that list item it modifies the JSON data associated with that location.
For Example AAA.BBB[0].CCC.DDD[5].EEE = 123
123 is a list item but I want the id to be saved as "AAA.BBB[0].CCC.DDD[5].EEE"
Would there be a better way to save the location in the id?
*Edit:
Sample Code:
JSON DATA: {"AAA":{"AAB":"Value1","AAC":"Value2","AAD":1,"AAE":"Value3","AAF":"{"ABC": "Value4"}}}
Soo the id for list item "Value4" would be AAA.AAF.ABC
function nodeIT(obj,output){
for (var x in obj){
if(!(obj[x] instanceof Object)){
//var str =JSON.stringify(obj); // Where im stuck!
output +="<li id='"+str+x +"'>";
output += (x + "=" + obj[x] + "<br />");
output +="</li>";
}
else if((obj[x] instanceof Object)){
var obj1 = obj[x];
output+="<li>" +x + "<ul>";
output=nodeIT(obj1,output);
}
}
output += "</ul></li>";
return output;
}
Instead of using the ID attribute and being forced to use a single string, you could take advantage of jQuery's .data() method, which lets you associate javascript objects with html elements.
So you do something like this when you're building the list elements:
var liElement = $('<li />')
.text(x + "=" + obj[x])
.data({
container: obj,
key: x
});
And then access the data later like this (where this refers to an li):
var container = $(this).data('container');
var key = $(this).data('key');
var value = container[key];
// .. modify value
container[key] = value;
Please see a full example here: http://jsfiddle.net/h38Ec/

Categories