how to loop trough arrays in json data using only javscript - javascript

Data source (JSON):
{
"photographers": [{
"name": "Mimi Keel",
"id": 243,
"city": "London",
"country": "UK",
"tags": ["portrait", "events", "travel", "animals"],
"tagline": "Voir le beau dans le quotidien",
"price": 400,
"portrait": "MimiKeel.jpg"
},
{
"name": "Ellie-Rose Wilkens",
"id": 930,
"city": "Paris",
"country": "France",
"tags": ["sports", "architecture"],
"tagline": "Capturer des compositions complexes",
"price": 250,
"portrait": "EllieRoseWilkens.jpg"
}
],
I am trying to loop trough the array contained in the key tags in the first photographers entry and display the all tags in a list item.
Heres what i got so far:
function fetchData() {
fetch("sample json file.json")
.then(response => response.json())
.then(data => {
console.log(data.photographers[0].tags[1])
// looping throw tags of a photographer
var output = "";
for (var i = 0; i <= data.photographers[0].tags.length; i++) {
for (keys in data.photographers[0].tags[i]) {
console.log(data.photographers[0].tags[i])
if (data.photographers[0].tags[i].hasOwnProperty(keys)) {
output += '<li>' +
'<a href="' + data.photographers[0].tags[i] +
'">' + data.photographers[0].tags[i] + '</a>' +
'</li>';
}
}
}
var update = document.getElementById('tags');
update.innerHTML = output;
})
}
fetchData();
I am open to any suggestion or correction of my code

Your loop can be made really simple. It has a couple of issues such as the one you mentioned, and another is dealing with multiple photographers and not just the first (Not sure if this is your actual use case):
Your code change: Remove your inner for loop as that's what duplicates everything:
for (var i = 0; i < data.photographers[0].tags.length; i++) {
console.log(data.photographers[0].tags[i])
}
Suggestion:
// same data given in the question
let data = { "photographers": [{ "name": "Mimi Keel","id": 243,"city": "London","country": "UK","tags": ["portrait", "events", "travel", "animals"],"tagline": "Voir le beau dans le quotidien","price": 400,"portrait": "MimiKeel.jpg" }, {"name": "Ellie-Rose Wilkens","id": 930,"city": "Paris","country": "France","tags": ["sports", "architecture"],"tagline": "Capturer des compositions complexes","price": 250,"portrait": "EllieRoseWilkens.jpg" }]};
// All photographers
for (let photographer of data.photographers) {
for (let tag of photographer.tags) {
console.log(tag);
// Here you get individual tag. Use it in your code like generating output.
}
}
// Just the first photographer
for (let tag of data.photographers[0].tags) {
console.log(tag);
// Here you get individual tag. Use it in your code like generating output.
}

Related

Show JSON data in table with selectbox

I want to select every data with same key in json from selectbox. For example, I want to select all values ​​with "author" key by putting them in the selectbox.
In the same way, I want to select the values ​​corresponding to the "country" key by putting them in a selectbox.
My JSON
"kitap": [
{
"author": "Chinua Achebe",
"country": "Nigeria",
"imageLink": "images/things-fall-apart.jpg",
"language": "English",
"link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
"pages": 209,
"title": "Things Fall Apart",
"year": 1958
},
{
"author": "Hans Christian Andersen",
"country": "Denmark",
"imageLink": "images/fairy-tales.jpg",
"language": "Danish",
"link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.\n",
"pages": 784,
"title": "Fairy tales",
"year": 1836
}
]
}
My javascript
let table2 = document.getElementById("tr2")
var books = fetch("kitap.json")
.then(res=> res.json())
.then(veri => {for(let data in veri ) {
for(deger of veri[data]) {
table2.innerHTML+= `
<td><select><option value="${deger.author}"></select></td>
<td><select><option value="${deger.country}"></select></td>
<td><select><option value="${deger.imageLink}"></select></td>
`
}
}})
how can i edit?
So this is one approach. The code is untested but should provide enough information for you to get started.
let table2 = document.getElementById("tr2");
let select1 = document.getElementById("ddlAuthor");
let select2 = document.getElementById("ddlCountry");
var books = fetch("kitap.json")
.then(res => res.json())
.then(veri => {
// Sets do not contain duplicates.
let setOfAuthors = new Set();
let setOfCountries = new Set();
for (let data in veri) {
for (deger of veri[data]) {
table2.innerHTML += `
<td><select><option value="${deger.author}"></select></td>
<td><select><option value="${deger.country}"></select></td>
<td><select><option value="${deger.imageLink}"></select></td>`
setOfAuthors.add(deger.author);
setOfCountries.add(deger.country);
}
// clear and fill <select> with <option>s.
PopulateDDL(select1, setOfAuthors);
PopulateDDL(select2, setOfCountries);
}
});
function populateDDL(ddl, setOfData) {
let distinctSortedArray = Array.from(setOfData).sort();
clearDDL(ddl);
for (var i = 0; i < distinctSortedArray.length; i++)
ddl.add(new Option(distinctSortedArray[i]));
}
function clearDDL(ddl) {
while (ddl.options.length) {
ddl.remove(0);
}
}

Javascript iterating through JSON file

{
"comments": [
{
"created_utc": 1622513325,
"text": "gdhg sgf sddsfsd fdsf"
},
{
"created_utc": 1622513188,
"text": "sfdg sgf fdgfdg"
}
]
}
How would you iterate over each object to see the text?
Something like..?
let data = fs.readFileSync(path.resolve(__dirname, 'comments.json'));
let comments = JSON.parse(data);
for(var i in comments){
for(var j in i) {
console.log("? " + j.text)
}
}
If you know the structure of your JSON will always be a comments object on the first level, containing a list of elements with created_utc and text, you can do as easy as the following code.
You don't need to nest the cycle as you only want to iterate over one list, then read the items and directly access to the text field of each item.
var jsonString = `{
"comments": [
{
"created_utc": 1622513325,
"text": "gdhg sgf sddsfsd fdsf"
},
{
"created_utc": 1622513188,
"text": "sfdg sgf fdgfdg"
}
]
}`;
let comments = JSON.parse(jsonString).comments;
comments.forEach(comment => {
console.log(comment.text);
});

Looping through items in an object for google sheets

I am trying to loop through an array that is part of a JSON object from a page speed insights call to add all of the unused javascript Urls to a google sheet using the script editor.
Here is an example of the JSON object:
"audits": {
"unused-javascript": {
"id": "unused-javascript",
"title": "Remove unused JavaScript",
"description": "Remove unused JavaScript to reduce bytes consumed by network activity. [Learn more](https://web.dev/unused-javascript/).",
"score": 0.43,
"scoreDisplayMode": "numeric",
"numericValue": 1350,
"numericUnit": "millisecond",
"displayValue": "Potential savings of 231 KiB",
"details": {
"type": "opportunity",
"headings": [
{
"key": "url",
"valueType": "url",
"subItemsHeading": {
"key": "source",
"valueType": "code"
},
"label": "URL"
},
{
"key": "totalBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceBytes"
},
"label": "Transfer Size"
},
{
"key": "wastedBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceWastedBytes"
},
"label": "Potential Savings"
}
],
"items": [
{
"url": "https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable",
"totalBytes": 140229,
"wastedBytes": 108197,
"wastedPercent": 77.15757011763822
},
{
"url": "https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js",
"totalBytes": 306716,
"wastedBytes": 106243,
"wastedPercent": 34.63892414884589
},
{
"url": "https://www.googletagmanager.com/gtm.js?id=GTM-KZ",
"totalBytes": 127214,
"wastedBytes": 21845,
"wastedPercent": 17.17151000374831
}
],
"overallSavingsMs": 1350,
"overallSavingsBytes": 236285
}
},
I am attempting to loop through the "items" array within the "unused-javascript" object and get all of the urls to show in google sheets.
Here is the code I have within the script editor. When I run this, only one URL shows on the sheet. However, I am trying to get all of the URLs added to the sheet.
function pageSpeed(Url) {
var key = "AIzaSyAyHY";
var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key;
var array = [];
if (key == "YOUR_API_KEY")
return "Please enter your API key to the script";
var response = UrlFetchApp.fetch(serviceUrl);
if (response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ((content != null) && (content["lighthouseResult"] != null)) {
if (content["captchaResult"]) {
var timetointeractive = content["lighthouseResult"]["audits"]["interactive"]["displayValue"].slice(0, -2);
var firstcontentfulpaint = content["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"].slice(0, -2);
var firstmeaningfulpaint = content["lighthouseResult"]["audits"]["first-meaningful-paint"]["displayValue"].slice(0, -2);
var speedindex = content["lighthouseResult"]["audits"]["speed-index"]["displayValue"].slice(0, -2);
var unusedJs = content["lighthouseResult"]["audits"]["unused-javascript"]["details"]["items"];
for (var i = 0; i < unusedJs.items.length; i++) {
var unusedUrl;
unusedUrl = unusedJs[i]["url"]
}
}
else {
var timetointeractive = "An error occured";
var firstcontentfulpaint = "An error occured";
var firstmeaningfulpaint = "An error occured";
var speedindex = "An error occured";
var unusedJs = "An error occured";
}
}
var currentDate = new Date().toJSON().slice(0, 10).replace(/-/g, '/');
array.push([timetointeractive, firstcontentfulpaint, firstmeaningfulpaint, speedindex, currentDate, "complete", unusedUrl]);
Utilities.sleep(1000);
return array;
}
}
Any and all help is appreciated!
You're on the right track.
Take a look below at my usage of Array.prototype.map. That's the simpler route.
Your for loop would work just as well IF you declared unusedUrl outside of (ie. before) the loop AND pushed to an existing array. As it is, there's an issue of scope, so unusedUrl is redeclared on every iteration, meaning you'll only assign the last iteration's value to unusedUrl.
Both solutions are below.
Using map
var content = {
lighthouseResult: {
audits: {
'unused-javascript': {
// Other stuff
details: {
// Other stuff
items: [
{
url:
'https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable',
totalBytes: 140229,
wastedBytes: 108197,
wastedPercent: 77.15757011763822,
},
{
url:
'https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js',
totalBytes: 306716,
wastedBytes: 106243,
wastedPercent: 34.63892414884589,
},
{
url: 'https://www.googletagmanager.com/gtm.js?id=GTM-KZ',
totalBytes: 127214,
wastedBytes: 21845,
wastedPercent: 17.17151000374831,
},
],
overallSavingsMs: 1350,
overallSavingsBytes: 236285,
},
},
},
},
}
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = items.map(item => item.url) // OR, using es6, items.map(({ url }) => url)
console.log(unusedUrls)
Using for
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = []
for (var i = 0; i < items.length; i++) {
unusedUrls.push(items[i]['url'])
}

I want some help in populating a tree structure on my webpage from flat structure without Parent/child values

I am trying to build a dynamic tree structure from the JSON response i receive. The JSON is as follows:
var projectViewData = [{
"projectTYpe": "Report",
"Doctor": "Abc",
"Patient": null,
"type": "xyz",
"document":"a.xls"
},{
"projectTYpe": "Report",
"Doctor": "Abc",
"Patient": "Smith",
"type": "xyz",
"document":"a.xls"
},
{
"projectTYpe": "Analysis",
"Doctor": "Abc",
"Patient": null,
"type": "xyz",
"document":"a.xls"
},
{
"projectTYpe": "Report",
"Doctor": "Abc",
"Patient": "Smith",
"type": "xyz",
"document":"a.xls"
}
];
The JSON can have null values which need to be ignored and next value from the object needs to be picked to plot next in the tree. The Object also don't have parent_id/child_id. My approach is to iterate through every object in json and adding it to an array.
This is the final structure I want to be dynamically generated on my page using javascript.
Below is the work i have done till now.
var array = ["<ul class=\"tree\">"];
for (projectdataElem in projectViewData)
{
array.push("<ul>");
var count = 0;
for (x in projectViewData[projectdataElem])
{
if(projectViewData[projectdataElem][x]==null )
{
}
else
{ if(x=='document'){
array.push("<li>" + projectViewData[projectdataElem][x] + "</li>");
for(var i = 0; i< count; i++)
{
array.push("</ul>"); }
}
else{
if((array.indexOf(projectViewData[projectdataElem][x]))== -1){
console.log(array.indexOf(projectViewData[projectdataElem][x]));
console.log(projectViewData[projectdataElem][x]);
//array.push("<li>" + projectViewData[projectdataElem][x] + "</li>");
array.push("<li>");
array.push(projectViewData[projectdataElem][x]);
array.push("</li>");
array.push("<ul>");
count += 1;
}
}
}
}
array.push("</ul>");
}
array.push("</ul>");
$("#list1").html(array.join(""));
//printList("string");
console.log(array);
Any leads would be highly appreciated.

Output object array loop in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have the following code. I'm trying to output each key value ("company" and "address") the different "city1, 2 ,3" object (list goes on and on in the real example). in to a <p> using javascript. I am feeling a bit lost since I've tried a lot of different ways but I can't get it to work. I believe it might be due to the structure. If it would only be one city there would be no problem.
var data = {
"city1":
[
{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
},
{
"company": "Hemköp",
"address": "Allegatan 26"
}
],
"city2":
[
{
"company": "Ica Nära",
"address": "Centrumvägen 7"
}
],
"city3":
[
{
"company": "Hora brothers kiosk",
"address": "Rövsgatan 43"
},
{
"company": "Microsoft",
"address": "Husvägen 38"
}
]
};
You can iterate the data object using for...in and then iterate the array inside with forEach.
var body = '';
for(var city in data) {
data[city].forEach(function(entry) {
body += '<p>' + entry.company + ', ' + entry.address + '</p>';
});
}
console.log(body);
If it's reasonable within your product requirements, you might consider using list elements rather than a simple <p>. Try to use the appropriate document.createElement methods rather than building a string. Something like:
var data = {
"city1": [{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
}, {
"company": "Hemköp",
"address": "Allegatan 26"
}],
"city2": [{
"company": "Ica Nära",
"address": "Centrumvägen 7"
}],
"city3": [{
"company": "Hora brothers kiosk",
"address": "Rövsgatan 43"
}, {
"company": "Microsoft",
"address": "Husvägen 38"
}]
};
var cityList = document.getElementById("city-list");
for (var cityName in data) {
if (data.hasOwnProperty(cityName)) {
var city = document.createElement("li");
var cityLabel = document.createElement("p");
cityLabel.textContent = cityName;
city.appendChild(cityLabel);
var companyList = document.createElement("ul");
city.appendChild(companyList);
var companies = data[cityName];
for (var i = 0; i < companies.length; ++i) {
var company = document.createElement("li");
company.textContent = companies[i].company + ": " + companies[i].address;
companyList.appendChild(company);
}
cityList.appendChild(city);
}
}
<ol id="city-list"></ol>
Similar to Ben's answer. I personally like plain for..in loops over foreaches in javascript, but its a preference.
var data = {
"city1":
[
{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
},
{
"company": "Hemköp",
"address": "Allegatan 26"
}
],
...
};
var html = "";
for(var city in data)
{
//you can append the city to the html here if you want
// html += "<h2>" + city + "</h2>";
for(var company in data[city])
{
for(var field in data[city][company])
{
html += "<p>" + field + ": " + data[city][company][field] + "</p>";
}
}
}

Categories

Resources