Getting specific value from object array for html injection - javascript

I'm trying to get a certain value from a Json file for html injection. The Json can have multiple arrays much more than in this example, but only the first array value of each array has certain value called title. Example json:
var placesdata= {
"Places": {
"Berlin": [
{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [
{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
I'm inserting all the values to HTML in a function that loops trough all of the arrays in the object. Here the problem is that I don't know how to insert the title value so that the HTML gets it. Tried numerous ways doing it but all failed. I'm trying to insert the title value at toimipistedata[key1][0].title:
function CreateAccordionTitles($container) {
for (var i = 0; i < Object.keys(placesdata).length; i++) {
var component =
'<div class="title">' +
'<i class="dropdown icon"></i>' +
placesdata[key1][0].title +
'</div>' +
'<div class="content styleSetSubAccordion">' +
'<div class="ui two column divided grid ' + Object.keys(placesdata)[i] + '\">' +
'</div>' +
'</div>'
if ($container.length) {
$container.append(component);
}
}
}
(The $container is an id/class for HTML element)
So how can I get the title value from the object arrays so that I can insert it with the HTML?
Tried to make a snippet about how it currently works and what needs to be changed in comments but failed something so it broke:
var placesdata= {
"Places": {
"Berlin": [
{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [
{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
function CreateTitles($container) {
for (var i = 0; i < Object.keys(placesdata).length; i++) {
var component =
'<li>' +
Object.keys(placesdata)[i] + //this needs to get the title value like this toimipistedata[key1][0].title
'<ul class="place ' + Object.keys(placesdata)[i] + '\">' +
'</ul>' +
'</li>'
if ($container.length) {
$container.append(component);
//CreateToimipisteContent(placesdata.Object.keys(placesdataa)[i], "." + Object.keys(placesdata)[i]); I need this to work
}
}
}
function CreateToimipisteContent(data, elementpos) {
for (var i = 0; i < data.length; i++) {
var dat = data;
var $txtp = $('<li>' + dat[i].location + '</li>').appendTo(elementpos);
$txtp.addClass(dat[i].buildings);
}
}
CreateTitles($("#Placement"));
CreateToimipisteContent(placesdata.Poliklinikat, ".Berlin"); // i dont want to use these like this they need to come form the CreateTitles function, these should be removed
CreateToimipisteContent(placesdata.Tutkimustoimenpiteet, ".Paris"); // i dont want to use these like this they need to come form the CreateTitles function, these should be removed
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="Placement"></ul>
<script src="jquery-3.3.1.min.js"></script>
</body>
</html>

You could use Array.prototype.find, which returns the first element that fulfils the supplied predicate.
I've got no idea what toimipistedata is so I'll give you as close an example as I can:
var title = placesdata.Places[city].find(x => x.title).title;
This works because any element in the placesdata.Places[city] array that has the title property set will be "truthy", so that object will be returned.

Just to expand on #ChristianScott's answer a bit, you could loop over placesdata["Places"] to get the city, and then use the find method to get the title.
So, for completeness:
var placesdata = {
"Places": {
"Berlin": [{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
let titles = []; // titles array
for (let city in placesdata["Places"]) { // for each city
titles.push(placesdata.Places[city].find(x => x.title).title); // find & push title
}
console.log(titles);

You can try this simple solution using for in:
var places = placesdata.Places;
for (var place in places) {
var component =
'<div class="title">' +
'<i class="dropdown icon"></i>' +
places[place][0].title +
'</div>' +
'<div class="content styleSetSubAccordion">' +
'<div class="ui two column divided grid ' + place + '\">' +
'</div>' +
'</div>'
if ($container.length) {
$container.append(component);
}
}

Related

Nested JSON to Numbered HTML Table using Javascript

I'm trying to generate HTML table from JSON
The JSON provided is deeply nested. With the help of this thread How do I loop through deeply nested properties of a JavaScript object?, I am able to get the values of the JSON but I am confused on how to generate the HTML table
var districts = {
"district": [{
"ration": 4,
"states": [{
"name": "Louisiana",
"population": 42383,
"cities": [{
"name": "Cavalero"
}]
}]
}, {
"ration": 1,
"states": [{
"name": "Colorado",
"population": 980,
"cities": []
}, {
"name": "Arkansas",
"population": 58998,
"cities": []
}, {
"name": "Illinois",
"population": 59333,
"cities": [{
"name": "Kenwood"
}]
}]
}, {
"ration": 2,
"states": [{
"name": "Washington",
"population": 83984,
"cities": [{
"name": "Conestoga"
}, {
"name": "Whitehaven"
}, {
"name": "Dellview"
}]
}, {
"name": "West Virginia",
"population": 38034,
"cities": []
}]
}]
};
var i, district, j, states, k, cities;
for (i = 0; i < districts.district.length; i++) {
district = districts.district[i];
print(i + 1, ". District", i + 1, "consists of following states", "--- ration", district.ration);
for (j = 0; j < district.states.length; j++) {
states = district.states[j];
var said = (states.cities.length > 0) ? ("consists of following cities") : ("");
print(i + 1, ".", j + 1, states.name, said, "--- population", states.population);
for (k = 0; k < states.cities.length; k++) {
cities = states.cities[k];
print(" ", i + 1, ".", j + 1, ".", k + 1, cities.name);
}
}
}
Run this on Ideone
Any pointers/help/suggestions appreciated
You will need to generate a table, like this:
var districts = {
"district": [{
"ration": 4,
"states": [{
"name": "Louisiana",
"population": 42383,
"cities": [{
"name": "Cavalero"
}]
}]
}, {
"ration": 1,
"states": [{
"name": "Colorado",
"population": 980,
"cities": []
}, {
"name": "Arkansas",
"population": 58998,
"cities": []
}, {
"name": "Illinois",
"population": 59333,
"cities": [{
"name": "Kenwood"
}]
}]
}, {
"ration": 2,
"states": [{
"name": "Washington",
"population": 83984,
"cities": [{
"name": "Conestoga"
}, {
"name": "Whitehaven"
}, {
"name": "Dellview"
}]
}, {
"name": "West Virginia",
"population": 38034,
"cities": []
}]
}]
};
//Start of the table, including header
var table = '<table><thead><tr><th>Num</th><th>District</th><th>Population</th><th>Ration</th></tr></thead><tbody>';
//Num
for (var i = 0; i < districts.district.length; i++) {
//District
var district = districts.district[i];
//First row
table += '<tr><td>' + (i + 1) + '</td><td>District ' + district.ration + ' consists of the following states:</td><td></td><td>' + district.ration + '</td></tr>';
//States
var states = district.states;
for (var j = 0; j < states.length; j++) {
table += '<tr><td></td><td>' + (i + 1) + '.' + (j + 1) + ' ' + states[j] + ((states[j].cities && states[j].cities.length) ? ' consists of following cities:' : '') + '</td><td>' + states[j].population + '</td><td></td></tr>';
//Cities
if (states[j].cities) {
for (var k = 0; k < states[j].cities; k++) {
table += '<tr><td></td><td>' + (i + 1) + '.' + (j + 1) + '.' + (k + 1) + ' ' + states[j].cities[k].name + '</td><td></td><td></td></tr>';
}
}
}
}
//End of the table
table += '</tbody></table>';
and then add table somewhere into your html.
if you want to generate the desired output as on that link, you can use
<ol>
<li></li>
<li>
<ol><li></li></ol>
<li>
</ol>
instead of table. generate it using javascript. you can use below code to generate your ordered list which should be inserted on the main ordered list tag.
var district = districts.district;
function generateCities(cities){
cities.map((city) => {
return (
"<li>"+ city.name + "</li>"
)
})
}
function generateStates(states, generateCities){
states.map((stat) => {
return (
"<li>"+stat.name + " consists of following cities --- population " + stat.population + "</li>"
+"<ol>" + generateCities(stat.cities) + "</ol>"
)
});
}
function generateMyHtml(district, generateStates){
district.map((dist, index) => {
return (
"<li> District "+ index + "consists of following states --- ration " + dist.ration + "</li>"
+"<ol>" + generateStates(dist.states) + "</ol>"
)
});
};
hope this is helpful

Create JSON object with same keys for API call

I'm trying to create a JSON object for an API call which has the following format:
....
"Key": "Value",
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "20",
"Width": "25",
"Height": "30"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "80"
}
},
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "15",
"Width": "24",
"Height": "27"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "50"
}
},
"Key": "Value",
....
I should add as many "Package" objects as needed. However, I've tried doing this in many different ways but every time that I parse the variable to be used the first objects get overwritten and I end up with only the last object.
This is what I'm trying at the moment, still with no luck:
var lineItems = '{';
for (var i=0;i<inputObject.packages.length;i++) {
lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
if (i !== inputObject.packages.length-1) {
lineItems += ',';
}
}
lineItems += '}';
lineItems = JSON.parse(lineItems);
How about numbering your packages, ie:
for (var i=0;i<inputObject.packages.length;i++) {
lineItems+='"Package" + i : { ... }'
}
edit: to get required result (as an array - because it's not JSON), here's an example:
var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);

Creating table from json using javascript

First of all I'm pretty new to javascript. I tried to create a table from json file. I read up some information and follow some tutorials, and I finally was able to create a table that appeared on the web browser. But I found out that the different arrays are always sorted, and it allows only unique values. For example here is the json:
var json = {
"data": [
{
"number": "13",
"position": "GK",
"name": "John"
},
{
"number": "2",
"position": "CB",
"name": "Bill"
},
{
"number": "26",
"position": "CB",
"name": "Nick"
}
And when I put the information in the table I'm creating it looks something like this:
| Number | Position | Name |
| 2 | GK | John |
| 13 | CB | Bill |
| 26 |undefined | Nick |
As you can see the numbers from json file does not match their names and the numbers are sorted, for example John is not number 2 but number 13. The other thing is it doesnt allow same values - there are 2 CB positions, but it shows only 1 and the other is shown as undefined.
Here is what I wrote so far:
JSONDataLouder = {
getPlayers: function(json) {
var object = {
"number": {}
, "position": {}
, "name": {}
};
var personData = null;
for (var i = 0; i < json.data.length; i++) {
personData = json.data[i];
object.number[personData.number] = 1;
object.position[personData.position] = 1;
object.name[personData.name] = 1;
}
var u = {
"number": []
, "position": []
, "name": []
};
for(var k in object.number) u.number.push(k);
for(var k in object.position) u.position.push(k);
for(var k in object.name) u.name.push(k);
return u;
}
,getTable: function(json) {
var obj = this.getPlayers(json);
var number = obj.number;
var position = obj.position;
var name = obj.name;
var table = this.createTable();
var headerRow = table.insertRow();
headerRow.insertCell().innerHTML = "Number";
headerRow.insertCell().innerHTML = "Position";
headerRow.insertCell().innerHTML = "Name"
for (var i = 0; i < number.length; i++) {
var secondRow = table.insertRow();
secondRow.style.textAlign="center";
secondRow.insertCell().innerHTML = number[i];
secondRow.insertCell().innerHTML = position[i];
secondRow.insertCell().innerHTML = name[i];
}
return table;
}
,render: function(mainDiv) {
$( mainDiv ).empty();
var json = {
"data": [
{
"number": "13",
"position": "GK",
"name": "John"
},
{
"number": "2",
"position": "CB",
"name": "Bill"
},
{
"number": "26",
"position": "CB",
"name": "Nick"
}
I know I misunderstood something when learning about pushing objects into array, and I tried to change it in any way, but it still appeares the same. Thank you in advance for your time.
I think the problem that you are experiencing is that in javascript, hashes are not ordered, so when you do for(var k in object.number), you can not expect each number to come out in the same order that you put it in.
Arrays, however will preserve order.
I don't think you need your object variable at all. I think you can just do this:
JSONDataLouder = {
getPlayers: function(json) {
var u = {
"number": [],
"position": [],
"name": []
};
var personData;
for (var i = 0; i < json.data.length; i++) {
personData = json.data[i];
u.number.push(personData.number);
u.position.push(personData.position);
u.name.push(personData.name);
}
return u;
}
Different test data would like give you even crazier results. There are actually a lot of issues in the code, but I think the main thing getting you off track is mixing your data structures. Before you think about the table itself, think about your intermediate data structure, namely some sort of (in effect) two dimensional array.
The thing is though, that you don't need an intermediate structure. You already have an array in your JSON.data. In your code, you are converting this array into something else.
Consider the following, which omits some of what you are doing, but cuts to the core of the table generation.
var json = {
"data": [
{
"number": "13",
"position": "GK",
"name": "John"
},
{
"number": "2",
"position": "CB",
"name": "Bill"
},
{
"number": "26",
"position": "CB",
"name": "Nick"
}
]
};
function objToTable(obj) {
var data = obj.data;
var output = '<table>';
for (var i = 0; i < data.length; i++) {
output += '<tr>';
output += '<td>' + data[i].number + '</td>';
output += '<td>' + data[i].position + '</td>';
output += '<td>' + data[i].name + '</td>';
output += '</tr>\n'; // added newline for console readability
}
output += '</table>';
return output;
}
console.log(objToTable(json));
Perhaps this could help you
var json = {
"data": [
{
"number": "13",
"position": "GK",
"name": "John"
},
{
"number": "2",
"position": "CB",
"name": "Bill"
},
{
"number": "26",
"position": "CB",
"name": "Nick"
}]
};
console.log('| Número | Posición | Nombre |');
$.each(json.data, function(id, item)
{
console.log(item.number + '|' + item.position + '|' + item.name + '|');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to display json data in a div when json data is in array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to display data received as Ajax callback in my app's page. The data somewhat looks like this:
"data": [
{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
},
The API contain more than 100 data, so how can we display these data in a html page. like this:
Name: Rehan
location: Pune
Description: hello hi
created by: 13692
user name: xyz
Edit
Alternatively, as suggested in comments / solutions, how to display the data as an HTML table?
You can use for to loop thru the array and contruct an HTML string. Use jQuery's .append() to add the string to the body.
var data = [{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
},
]
var htmlText = '';
for (var key in data) {
htmlText += '<div class="div-conatiner">';
htmlText += '<p class="p-name"> Name: ' + data[key].name + '</p>';
htmlText += '<p class="p-loc"> Location: ' + data[key].location + '</p>';
htmlText += '<p class="p-desc"> Description: ' + data[key].description + '</p>';
htmlText += '<p class="p-created"> Created by: ' + data[key].created_by + '</p>';
htmlText += '<p class="p-uname"> Username: ' + data[key].users_name + '</p>';
htmlText += '</div>';
}
$('body').append(htmlText);
.div-conatiner {
background-color: #eeeeee;
margin-bottom: 5px;
padding: 5px;
}
.div-conatiner p {
margin : 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
UPDATE: Another option is using map to loop thru the array and use Template literals to construct the HTML
var data = [{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
},
]
var htmlText = data.map(function(o){
return `
<div class="div-conatiner">
<p class="p-name"> Name: ${o.name}</p>
<p class="p-loc"> Location: ${o.location}</p>
<p class="p-desc"> Description: ${o.description}</p>
<p class="p-created"> Created by: ${o.created_by}</p>
<p class="p-uname"> Username: ${o.users_name}</p>
</div>
`;
});
$('body').append(htmlText);
.div-conatiner {
background-color: #eeeeee;
margin-bottom: 5px;
padding: 5px;
}
.div-conatiner p {
margin: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try this:
<div id="json"></div>
<script>
var obj = {"data": [
{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
}
]}
var divId = document.getElementById("json")
for(var i=0;i<obj.data.length;i++)
for(var keys in obj.data[i]){
console.log(keys +"-->"+obj.data[i][keys]);
divId.innerHTML = divId.innerHTML + "<br/>"+ keys +"-->"+obj.data[i][keys];
}
</script>
Fiddle : http://jsfiddle.net/Sourabh_/1m2tjth3/
You can modify this as per your requirement.
Assuming you have a table with id #table, loop through the json object and append a row for every object item:
var jsonObj = { ... }
for (i in jsonObj) {
for (n in jsonObj[i]) {
$('#table > tbody').append('<tr><th>' + n + '</th><td>' + jsonObj[i][n] + '</td></tr>');
}
}
var data = [
{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
}];
for (i=0;i<=data.length;i++) {
for (n in data[i]) {
$('#table > tbody').append('<tr><th>' + n + '</th><td>' + data[i][n] + '</td></tr>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table">
<tbody>
</tbody>
</table>

Getting value from JSON when it is an object in an array in an object in an array - if that makes sense?

I have been working on displaying values from a JSON feed and - with a great deal of thanks to help on the many previous posts I have read here - I can now write (display in browser) all the values of my objects in the main array BUT for the values of the 'name' objects which are 'nested' in an array > object > array > object > proprty:value structure (as below). Wondering if anyone might me kind enough to help me find a way to interate and display this level successfully - I feel I have run out of ideas on it at the moment :-(
Very thankful for an ideas. I have been using standard JavaScript not JQuery I should add.
var foo=[
{
"subjects":
[
"A1",
"SB2"
],
"title": "Box World",
"first_pub": "2013-12",
"characters":
[
{
"name":
{
"given": "Maxwell",
"honourific": "",
"family": "Smart"
},
"id": "MS34"
},
{
"name":
{
"given": "Samantha",
"honourific": "",
"family": "Stevens"
},
"id": "SS81"
} // end creators object 2
],
"publisher": "Galactic Publishing"
},
{
"subjects":
[
"A133",
"PB82"
],
"title": "Octonautica",
"first_pub": "2010",
"characters":
[
{
"name":
{
"given": "Peso",
"honourific": "Doctor",
"family": ""
},
"id": "MS34"
},
{
"name":
{
"given": "Barnacle",
"honourific": "Captain",
"family": ""
},
"id": "SS82"
}
],
"publisher": "Neptune House"
}
]
var obj_set = foo ;
for (var key in obj_set) {
document.write("\<h3\> Publication " + key + "\<\/h3\>" );
var obj = obj_set[key];
document.write("\<ol\>");
for (var prop in obj) {
document.write("\<li\>" + prop + " = " + obj[prop] + "\<\/li\>" );
}
document.write("\<\/ol\>");
}
//END MAIN KEY LOOP
Try this instead:
var i, j;
// iterate over main array foo
for (i=0; i<foo.length; i++) {
// iterate over characters array
for(j=0; j<foo[i].characters.length; j++) {
// each item contains an object "name"
var name = foo[i].characters[j].name;
console.log(name.honorific + ' ' + name.given + ' ' + name.family);
}
}

Categories