Why do I keep on getting null in the console log? - javascript

In the JS, I am creating an input element which will be nested inside a div with id "scripts" on the html. I attach a value to that input field via JS and later on I want to catch the value of the input in another JS function. The problem is that when I run the page in the inspect element I can see that there is a value in the input that I created, that input has id "spam_key", but the function that I have created to access and get the value out of the input element is not working properly. If I go to the console, and write console.log(str) I am getting null as result.
Here is what I have in the HTML:
<div id="scripts" name="scripts">
</div>
This is the HTML when I run the page and the input field is created:
<div id="scripts" name="scripts">
<input type="number" id="spam_key" value="239">
</div>
Now, this is my JS:
var c = 0;
var a;
var b;
function counter() {
return c++;
}
$(document).ready(function () {
var url = "https://graph.facebook.com/v3.2/...";
$.getJSON(url, function (data) {
var items = [];
$.each(data.data, function (i, obj) {
//$('#target').append($('<div/>', { id: 'dummy' + i }))
var text = '<p class="review_text">' + obj.review_text + '</p>'
var date = '<p class="date">' + obj.created_time + '</p>'
a = counter();
$("#carousel").find("[data-index='" + i + "']").append(text, date)
});
$('#scripts').append('<input type="number" id="spam_key" value= ' + a + '>');
});
});
And this is what I use to get the value of the input element:
var str;
$(document).ready(function () {
element = document.getElementById('spam_key');
if (element !== null) {
str = element.value;
}
else {
str = null;
}
});
Here the value of str should be appled:
$(document).ready(function () {
var wrapper = document.getElementById("carousel");
var myHTML = '';
for (b = 0; b <= str; b++) {
myHTML += '<div id="review" data-index=' + (b) + '></div>';
}
wrapper.innerHTML = myHTML
});

What I've done is to move the body of your input-retrieval-function from the second $(document).ready() to the callback function of your getJSON method after you've created the input element. This way we can make sure to access it after the element is created. I've also added a var str; to the global scope where you store the value.
Hope that helps.
var c = 0;
var a;
var b;
var str;
function counter() {
return c++;
}
$(document).ready(function () {
var url = "https://graph.facebook.com/v3.2/...";
$.getJSON(url, function (data) {
var items = [];
$.each(data.data, function (i, obj) {
//$('#target').append($('<div/>', { id: 'dummy' + i }))
var text = '<p class="review_text">' + obj.review_text + '</p>'
var date = '<p class="date">' + obj.created_time + '</p>'
a = counter();
$("#carousel").find("[data-index='" + i + "']").append(text, date)
});
$('#scripts').append('<input type="number" id="spam_key" value= ' + a + '>');
element = document.getElementById('spam_key');
if (element !== null) {
str = element.value;
}
else {
str = null;
}
var wrapper = document.getElementById("carousel");
var myHTML = '';
for (b = 0; b <= str; b++) {
myHTML += '<div id="review" data-index=' + (b) + '></div>';
}
wrapper.innerHTML = myHTML
});
});

Here is a sample from the JSON:
{
"data": [
{
"has_review": true,
"review_text": "Mng sum zadovolna se bese \ud83d\udc4c\ud83c\udffc",
"recommendation_type": "positive",
"created_time": "December 6, 2018",
"open_graph_story": {
"id": "1924663150981821",
"message": "Mng sum zadovolna se bese \ud83d\udc4c\ud83c\udffc",
"start_time": "December 6, 2018",
"type": "sellers.rates",
"data": {
"recommendation_type": "positive",
"review_text": "Mng sum zadovolna se bese \ud83d\udc4c\ud83c\udffc",
"is_hidden": false,
"language": "mk",
"seller": {
"id": "2075976265961628",
"title": "My Spa Home & Office Massage - \u041c\u0430\u0441\u0430\u0436\u0430 \u0432\u043e \u0432\u0430\u0448\u0438\u043e\u0442 \u0434\u043e\u043c \u0438\u043b\u0438 \u0440\u0430\u0431\u043e\u0442\u043d\u043e \u043c\u0435\u0441\u0442\u043e",
"type": "place",
"url": "https://www.facebook.com/myspamk/"
},
"has_review_update": false
}
},
"has_rating": false
},
{
"has_review": true,
"review_text": "\u041e\u0434\u043b\u0438\u0447\u043d\u043e \u0438\u0441\u043a\u0443\u0441\u0442\u0432\u043e. \u0420\u0435\u0442\u043a\u043e \u0441\u0430\u043a\u0430\u043c \u043c\u0430\u0441\u0430\u0436\u0438, \u0437\u0430\u0448\u0442\u043e \u043c\u0438 \u0441\u0435 \u043d\u0435\u043f\u0440\u0438\u0458\u0430\u0442\u043d\u0438 \u0447\u0435\u0441\u0442\u043e, \u043d\u043e, \u043e\u0432\u0430 \u0442\u043e\u043f\u043b\u043e \u0433\u043e \u043f\u0440\u0435\u043f\u043e\u0440\u0430\u0447\u0443\u0432\u0430\u043c! \u0411\u0440\u0430\u0432\u043e \u0434\u0435\u0447\u043a\u0438. \u2764",
"recommendation_type": "positive",
"created_time": "December 5, 2018",
"open_graph_story": {
"id": "1145960125557706",
"message": "\u041e\u0434\u043b\u0438\u0447\u043d\u043e \u0438\u0441\u043a\u0443\u0441\u0442\u0432\u043e. \u0420\u0435\u0442\u043a\u043e \u0441\u0430\u043a\u0430\u043c \u043c\u0430\u0441\u0430\u0436\u0438, \u0437\u0430\u0448\u0442\u043e \u043c\u0438 \u0441\u0435 \u043d\u0435\u043f\u0440\u0438\u0458\u0430\u0442\u043d\u0438 \u0447\u0435\u0441\u0442\u043e, \u043d\u043e, \u043e\u0432\u0430 \u0442\u043e\u043f\u043b\u043e \u0433\u043e \u043f\u0440\u0435\u043f\u043e\u0440\u0430\u0447\u0443\u0432\u0430\u043c! \u0411\u0440\u0430\u0432\u043e \u0434\u0435\u0447\u043a\u0438. \u2764",
"start_time": "December 5, 2018",
"type": "sellers.rates",
"data": {
"recommendation_type": "positive",
"review_text": "\u041e\u0434\u043b\u0438\u0447\u043d\u043e \u0438\u0441\u043a\u0443\u0441\u0442\u0432\u043e. \u0420\u0435\u0442\u043a\u043e \u0441\u0430\u043a\u0430\u043c \u043c\u0430\u0441\u0430\u0436\u0438, \u0437\u0430\u0448\u0442\u043e \u043c\u0438 \u0441\u0435 \u043d\u0435\u043f\u0440\u0438\u0458\u0430\u0442\u043d\u0438 \u0447\u0435\u0441\u0442\u043e, \u043d\u043e, \u043e\u0432\u0430 \u0442\u043e\u043f\u043b\u043e \u0433\u043e \u043f\u0440\u0435\u043f\u043e\u0440\u0430\u0447\u0443\u0432\u0430\u043c! \u0411\u0440\u0430\u0432\u043e \u0434\u0435\u0447\u043a\u0438. \u2764",
"is_hidden": false,
"language": "mk",
"seller": {
"id": "2075976265961628",
"title": "My Spa Home & Office Massage - \u041c\u0430\u0441\u0430\u0436\u0430 \u0432\u043e \u0432\u0430\u0448\u0438\u043e\u0442 \u0434\u043e\u043c \u0438\u043b\u0438 \u0440\u0430\u0431\u043e\u0442\u043d\u043e \u043c\u0435\u0441\u0442\u043e",
"type": "place",
"url": "https://www.facebook.com/myspamk/"
},
"has_review_update": false
}
},
"has_rating": false
},
{
"has_review": true,
"review_text": "The best massage in Skopje, highly recommend!",
"recommendation_type": "positive",
"created_time": "November 28, 2018",
"open_graph_story": {
"id": "10214943185147892",
"message": "The best massage in Skopje, highly recommend!",
"start_time": "November 28, 2018",
"type": "sellers.rates",
"data": {
"recommendation_type": "positive",
"review_text": "The best massage in Skopje, highly recommend!",
"is_hidden": false,
"language": "en",
"seller": {
"id": "2075976265961628",
"title": "My Spa Home & Office Massage - \u041c\u0430\u0441\u0430\u0436\u0430 \u0432\u043e \u0432\u0430\u0448\u0438\u043e\u0442 \u0434\u043e\u043c \u0438\u043b\u0438 \u0440\u0430\u0431\u043e\u0442\u043d\u043e \u043c\u0435\u0441\u0442\u043e",
"type": "place",
"url": "https://www.facebook.com/myspamk/"
},
"has_review_update": false
}
},
"has_rating": false
},

Related

Select filter hides all the items in the list

I am trying to create a select dropdown filter which dynamically gets its values and data from rest api.
Here is my code
HTML
<div class="container">
<select data-filter="season" class="filter_category_name filter form-control"></select>
<div class="listContent" id="listitem"></div>
</div>
JS
var data = [{
"category_name": "1",
"title": "One One",
"more": [{
"details": "some details"
}]
},
{
"category_name": "1",
"title": "One Two",
"more": [{
"details": "some details"
}]
},
{
"category_name": "2",
"title": "Two One",
"more": [{
"details": "some details"
}]
},
{
"category_name": "3",
"title": "Three One",
"more": [{
"details": "some details"
}]
}];
let listItems = "",
categoryAll = "";
for(var i = 0;i < data.length; i++) {
var title = data[i].title,
category_name = data[i].category_name;
listItems += "<a onclick='createAVideoContainer(" + i + ")'><div class='listItem'><p>" + title + "</p></div></div></a>";
if (categoryAll.indexOf("<option value='" + category_name + "'>" + category_name + "</option>") == -1) {
categoryAll += "<option value='" + category_name + "'>" + category_name + "</option>";
}
}
$("#listitem").html(listItems);
$(".filter_category_name").append(categoryAll);
var filtersObject = {};
$(".filter").on("change",function() {
var filterName = $(this).data("filter"),
filterVal = $(this).val();
if (filterVal == "") {
delete filtersObject[filterName];
} else {
filtersObject[filterName] = filterVal;
}
var filters = "";
for (var key in filtersObject) {
if (filtersObject.hasOwnProperty(key)) {
filters += "[data-"+key+"='"+filtersObject[key]+"']";
}
}
if (filters == "") {
$(".listItem").show();
} else {
$(".listItem").hide();
$(".listItem").hide().filter(filters).show();
}
});
But for some reason it hides all the items and nothing change after changing the options
I want to initially load all the items and then filter based on the option
I want the select element to dynamically create the options with the values of the category names like the first option should have the value of cars1 and display all the other objects with the same category_name.
Note: The entire code is wrapped inside an async function which renders on page load.
Here is a proper working js fiddle with the above problem
Based on your fiddle code, it would be better to filter the <a> items within the listItem area based on season, as that is the filter that is built, instead of trying to show/hide the entire listItem area.
The two minor code changes to achieve the desired result, is at these two code points:
Add a data-season reference here, to the <a> tags, with the category_name value:
listItems += '<a data-season="' + category_name + '" '
+ "onclick='createAVideoContainer(" + i + ")'><div class='listItem'><p>"
+ title + "</p></div></a>";
Change the filtering to filter on the <a> tags for the data-season that you build:
if (filters == "") {
$("a").show();
} else {
$("a").hide();
$("a").filter(filters).show();
}
Integrating those two changes into your fiddle example code, try the runnable example below:
var data = [
{
"category_name": "1",
"title": "One One",
"more": [
{
"details": "some details"
}
]
},
{
"category_name": "1",
"title": "One Two",
"more": [
{
"details": "some details"
}
]
},
{
"category_name": "2",
"title": "Two One",
"more": [
{
"details": "some details"
}
]
},
{
"category_name": "3",
"title": "Three One",
"more": [
{
"details": "some details"
}
]
},
];
let listItems = "",
categoryAll = "";
for(var i = 0; i < data.length; i++) {
var title = data[i].title,
category_name = data[i].category_name;
listItems += '<a data-season="' + category_name + '"'
+ "onclick='createAVideoContainer(" + i + ")'><div class='listItem'><p>"
+ title + "</p></div></a>";
if (categoryAll.indexOf("<option value='" + category_name + "'>" + category_name + "</option>") == -1) {
categoryAll += "<option value='" + category_name + "'>" + category_name + "</option>";
}
}
$("#listitem").html(listItems);
$(".filter_category_name").append(categoryAll);
var filtersObject = {};
//on filter change
$(".filter").on("change",function() {
var filterName = $(this).data("filter"),
filterVal = $(this).val();
if (filterVal == "") {
delete filtersObject[filterName];
} else {
filtersObject[filterName] = filterVal;
}
var filters = "";
for (var key in filtersObject) {
if (filtersObject.hasOwnProperty(key)) {
filters += "[data-"+key+"='"+filtersObject[key]+"']";
}
}
if (filters == "") {
$("a").show();
} else {
$("a").hide();
$("a").filter(filters).show();
}
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="container">
<select data-filter="season" class="filter_category_name filter form-control"></select>
<div class="listContent" id="listitem">
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.3/dist/umd/popper.min.js" integrity="sha384-eMNCOe7tC1doHpGoWe/6oMVemdAVTMs2xqW4mwXrXsW0L84Iytr2wi5v2QjrP/xp" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js" integrity="sha384-cn7l7gDp0eyniUwwAZgrzD06kc/tftFf19TOAs2zVinnD/C7E91j9yyk5//jjpt/" crossorigin="anonymous"></script>
Here's the updated fiddle with the same change applied.

How can I get Google App Script is to loop and not only pull from the first row

function buildReport() {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Invalid Login MM Pull Internal");
var ws2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Invalid Login External MM Pull External");
var data = ws.getRange("A2:G" + ws.getLastRow()).getValues();
var data2 = ws2.getRange("A2:G" + ws2.getLastRow()).getValues();
let payload = buildAlert(data);
let payload2 = buildAlert(data2)
sendAlert(payload);
}
//buildAlert Fuction
function buildAlert(data) {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Invalid Login MM Pull Internal");
var data = ws.getRange("A2:G" + ws.getLastRow()).getValues();
for (var i = 0; i < data.length; i++){
if (data[i][5] !== "SLACK_SENT")
var ofo = 1;
var restaurant = 2;
var name = 3;
var email = 4;
var sent = 5;
let payload = {
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":bell: Invalid Creds :bell:"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": data[i][2] + " has invalid creds for " + data[i][1]
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Please contact have AE contact " + data[i][3] + " at " + data[i][4]
}
},
]
};
ws.getRange(2 + i,7).setValue("SLACK_SENT");
}
};
(function buildAlert(data2) {
var ws2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Invalid Login External MM Pull External");
var data2 = ws2.getRange("A2:G" + ws2.getLastRow()).getValues();
for (var i = 0; i < data2.length; i++){
if (data2[i][5] !== "SLACK_SENT")
var ofo = 1;
var restaurant = 2;
var name = 3;
var email = 4;
var sent = 5;
let payload = {
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":bell: Invalid Creds :bell:"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": data2[i][2] + " has invalid creds for " + data2[i][1]
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Please contact have AE contact " + data2[i][3] + " at " + data2[i][4]
}
},
]
};
ws2.getRange(2 + i,7).setValue("SLACK_SENT");
}
});
function sendAlert(payload) {
const webhook = "https://hooks.slack.com/services/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";
var options = {
"method": "post",
"contentType": "application/json",
"muteHttpExceptions": true,
"payload": JSON.stringify(payload)
};
try {
UrlFetchApp.fetch(webhook, options);
} catch(e) {
Logger.log(e);
}
};
**Trying to send slack message from a google sheet but right now it is only pulling from the first row and it does not loop.
The only thing that loops is when I run the code it populates a cell marking it as SLACK_SENT. Feel free to ask me any questions or need to clarify anything. I am pulling from two spreadsheets and want to send slack for both sheets.
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');//data sheet
const osh = ss.getSheetByName('Sheet2');//output sheet
const [hA, ...vs] = sh.getDataRange().getValues();
let col = {};
let oA = [];//data desired
hA.forEach((h,i) => col[h] = i+1);
vs.forEach(r => {
if(r[col['columntitle desired ']] == "value desired") {
oA.push(r);// push entire row
}
});
osh.getRange(sh.getLastRow() + 1, 1, oA.length, oA[0].length).setValues(oA);

JSON add value on click

I'm trying to make a site of restaurant and now doing some table reservation. So far have one problem:
I have a JSON of tables and want to add date (day/time) to it, when table was clicked.
The problem's next - when I click on some table, the date adds to all JSON elements. And I wand to add it only to the element I clicked.
Here is link to codepen:
https://codepen.io/wilchilly/pen/qBEvegW
(To see the result click on some table and open console)
My HTML:
<p class="href-to italic" id="showMore">Show tables</p>
<div class="wrapper" id="wrapper">
<div class="tables-wrapper" id="tables-wrapper"></div>
</div>
JS:
fetch('tables.json')
.then(response => response.json())
.then(json => {
const myJson = json;
let showTables = document.getElementById('showMore');
//show elements on page
function loadGoods(data) {
let out = '';
for (let key in data) {
if (data[key].isAvailable == false) {
out += '<div class="single-table not-available" data-name="' + data[key]['name'] + '" data-art="' + data[key]['id'] + '">';
out += '<h4>' + data[key]['name'] + '</h4>';
out += '<p>' + data[key]['location'] + '</p>';
out += '</div>';
} else {
out += '<div class="single-table" data-name="' + data[key]['name'] + '" data-art="' + data[key]['id'] + '">';
out += '<h4>' + data[key]['name'] + '</h4>';
out += '<p>' + data[key]['location'] + '</p>';
out += '</div>';
}
}
$('#tables-wrapper').html(out);
}
//set Date (day/time)
function setDate() {
for (let key in myJson) {
myJson[key]['date']['day'] = '10/02';
myJson[key]['date']['time'] = '20:00';
}
console.log(myJson);
}
showTables.addEventListener('click', function () {
loadGoods(myJson);
let singleTable = document.getElementsByClassName('single-table');
Array.from(singleTable).forEach(function (element) {
element.addEventListener('click', setDate);
});
});
})
JSON:
[
{
"id": 0,
"index": 0,
"name": "Table 1",
"capacity": 5,
"isAvailable": true,
"location": "Bar",
"date": {
"day": " ",
"time": ""
}
},
{
"id": 1,
"index": 1,
"name": "Table 2",
"capacity": 5,
"isAvailable": true,
"location": "Patio",
"date": {
"day": " ",
"time": " "
}
},
{
"id": 2,
"index": 2,
"name": "Table 3",
"capacity": 5,
"isAvailable": true,
"location": "Bar",
"date": {
"day": " ",
"time": " "
}
},
{
"id": 3,
"name": "Table 4",
"capacity": 6,
"isAvailable": true,
"location": "Inside",
"date": {
"day": " ",
"time": " "
}
}
]
I found a solution. This might be helpful for someone with a similar question.
function setDate() {
let inputDay = document.getElementById('form-data').value;
let inputTime = document.getElementById('form-time').value;
for (let i = 0; i < myJson.length; i++) {
if (this.getAttribute('data-art') == myJson[i].id) {
myJson[i]['date']['day'] = inputDay;
myJson[i]['date']['time'] = inputTime;
}
}
}
Just use the index from the iteration on table creation as id (or any attr you like) for example (you will probably need a classic for or a foreach) and then, in the event you attached pass the click event as param. Finally you just use the event.target to get the id (or the attr you choose) of the element and use it in the setDate func.

How to parse nested JSON in Javascript?

I am trying to parse and show JSON data (product catalog) using XMLHttpRequest method. I am able to display the brands and their names, but not able to showcase list of products progmatically.
Here is the sample JSON request:
{
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
}
Right now I am using following code to show data in tabluar form:
function loadJSON() {
var data_file = "http://localhost/AJAX/productcatalog.json";
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = function () {
if ((http_request.readyState == 4) && (http_request.status == 200)) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
data = '<table border="2"><tr><td>Type</td><td>Brand</td><td>Price</td></tr>';
var i = 0;
debugger;
for (i = 0; i < jsonObj["products"].laptop.length; i++)
{
obj = jsonObj["products"].laptop[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
for (i = 0; i < jsonObj["products"].cellphone.length; i++)
{
obj = jsonObj["products"].cellphone[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
for (i = 0; i < jsonObj["products"].tablets.length; i++)
{
obj = jsonObj["products"].tablets[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
data += '</table>';
document.getElementById("demo").innerHTML = data;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
Question What is the way to fetch product list , i.e. products, cellphone and tablets ? Right now I have hardcoded that in order to fetch complete list of brands. Please advice. (I want to use plain javascript and not jquery)
Thanks!
It sounds like what you're missing is the "How do I iterate over an object when I don't know all the keys".
An object is a set of key, value pairs. You can use for/in syntax: for( var <key> in <object> ){} to get each key.
For your use case it might be something like:
var products = jsonObject['products'];
for( var productName in products ){
//productName would be "laptop", "cellphone", etc.
//products[productName] would be an array of brand/price objects
var product = products[productName];
for( var i=0; i<product.length; i++ ){
//product[i].brand
//product[i].price
}
}
In practice, I might use something a little less verbose, but this makes it easier to understand what is going on.
To achieve the expected i have used for loop and HTML DOM createElement() Method
var product_catalog = {
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
};
var output = document.querySelector('#product tbody');
function build(JSONObject) {
/**get all keys***/
var keys = Object.keys(JSONObject);
/**get all subkeys***/
var subkeys = Object.keys(JSONObject[keys]);
console.log(subkeys);
/**loop sub keys to build HTML***/
for (var i = 0, tr, td; i < subkeys.length; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode(subkeys[i]));
tr.appendChild(td);
output.appendChild(tr);
}
};
build(product_catalog);
HTML:
Coepen URL for reference- http://codepen.io/nagasai/pen/xOOqMv
Hope this works for you :)
Look at this example:
var x = data.key1.children.key4;
var path = "data";
function search(path, obj, target) {
for (var k in obj) {
if (obj.hasOwnProperty(k))
if (obj[k] === target)
return path + "['" + k + "']"
else if (typeof obj[k] === "object") {
var result = search(path + "['" + k + "']", obj[k], target);
if (result)
return result;
}
}
return false;
}
//Then for evry node that you need you can call the search() function.
var path = search(path, data, x);
console.log(path); //data['key1']['children']['key4']
I think this is what you're asking about, you can use Object.keys to get the properties of an object, then loop through them afterward.
var data = {
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
}
var typesOfProducts = Object.keys(data.products)
console.log(typesOfProducts)
document.getElementById('output').textContent = typesOfProducts.toString()
//Then, to loop through
var i = -1,
len = typesOfProducts.length
function handleProduct(productType) {
console.log("This is the " + productType + " data.")
console.log(data.products[productType])
}
while (++i < len) {
handleProduct(typesOfProducts[i])
}
<div id="output"></div>
It sounds like what you're looking for is just an array of the keys of the "products" object. Example:
Products: ["laptop", "cellphone", "tablets"];
If so, I would just run your json object through javascript's Object.keys() method.
var jsonObj = JSON.parse(http_request.responseText);
var products = Object.keys(jsonObj.products);
// products = ["laptop", "cellphone", "tablets"];

How to iterate JSON Array in Jquery

I have this below type of array. I want to iterate this array in JavaScript. How is this possible?
{
"result": true,
"data": [
{
"ID": 1,
"stage_ID": 1,
"badge_type_ID": 1,
"name": "Despertar da Força",
"description": "Fazer a primeira SuperAtividade",
"type": "",
"image_static": "url123.jpg",
"image_animated": "",
"SQL": "",
"published": 1
},
{
"ID": 2,
"stage_ID": 1,
"badge_type_ID": 1,
"name": "Super 3",
"description": "Fazer 3 SuperAtividades",
"type": "",
"image_static": "urlimage123.png",
"image_animated": "",
"SQL": "",
"published": 1
}
etc
I tried the following script and it is returning "undefined", "undefined".
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(data) {
var output= "<ol>";
for (var i in data) {
output += "<li>" + data[i].ID + "</li>"
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});
Any solutions ? Thanks!
You can try converting to Json Object
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(data) {
var output= "<ol>";
var jsondata = $.JSON.parse(data); // Json object Convertion
for (var i in data) {
output += "<li>" + data[i].ID + "</li>"
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});
You are trying to access an undefined property using data[i].ID .
When you are getting response from your getJSON() function then you need to call the response with a name and then you can access any inner property using this name .
Now if you want to iterate using data key/value on myResponse variable then you need to do this.
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(myResponse) {
var output= "<ol>";
var dataCount = myResponse.data.length;
for (var i = 0; i < dataCount; i++) {
output += "<li>" + myResponse.data[i].ID + "</li>";
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});

Categories