How to retrieve array inside array in javascript? - javascript

Here is my Json array. I want to retrieve child arrays and I need to display all the invoices details under the project section. Please check the attached screenshot. In the screenshot you can see only last invoice details only displaying to all other projects. The last invoice number 1005 is showing for all. How can I show invoice details based on the project details?
When child row is empty,project details (parent) also not showing.Am getting projectinvoicesection: [] Array 0. I need to display project details and no record found in invoice section. But now am getting array zero.
[{
"parent": {
"project_ID": "1",
"project_title": "Network and Telephone Points",
"particulars": "Test Description",
"project_amount": "10000.00",
"type": "One Time",
},
"child": [{
"invoice_No": "1002",
"received_Amt": "0.00",
"invoice_amount": "472.50",
"proje_ID": "1",
"invoice_Date": "2021-08-31"
}]
},
{
"parent": {
"project_ID": "2",
"project_title": "Configuration and Programming",
"particulars": "test description",
"project_amount": "2000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1004",
"received_Amt": "0.00",
"invoice_amount": "245.70",
"proje_ID": "2",
"invoice_Date": "2021-08-30"
}]
},
{
"parent": {
"project_ID": "3",
"project_title": "Coffee ERP",
"particulars": "test",
"project_amount": "50000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1000",
"received_Amt": "0.00",
"invoice_amount": "1820.70",
"proje_ID": "3",
"invoice_Date": "2021-08-19"
},
{
"invoice_No": "1001",
"received_Amt": "0.00",
"invoice_amount": "1773.45",
"proje_ID": "3",
"invoice_Date": "2021-08-24"
}
]
},
{
"parent": {
"project_ID": "6",
"project_title": "sample project new design",
"particulars": "Test Project new",
"project_amount": "4000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1005",
"received_Amt": "0.00",
"invoice_amount": "283.50",
"proje_ID": "6",
"invoice_Date": "2021-08-21"
}]
}
]
I have tried this code below:
for (var i = 0; i < new_data.projectinvoicesection.length; i++) {
var sl = i + 1;
//alert(t6)
var t1 = new_data.projectinvoicesection[i]['parent'].project_amount;
//alert(t1)
var t2 = new_data.projectinvoicesection[i]['parent'].particulars;
var t3 = new_data.projectinvoicesection[i]['parent'].project_ID;
var t4 = new_data.projectinvoicesection[i]['parent'].project_title;
var t5 = new_data.projectinvoicesection[i]['parent'].type;
var t56 = new_data.projectinvoicesection[i]['parent'].period_type;
var object = new_data.projectinvoicesection[i]['child'];
var tr = "<tr data-toggle='collapse' data-target='#demo" + t3 + "' style='background-color: #337ab7;color: white;' class='accordion-toggle'><td>" + sl + "</td><td>" + t4 + "</td><td>" + t1 + "</td><td style='white-space: nowrap;'>" + t5 + " " + t56 + "</td><td><button class='open-button-project-edit btn' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#exampleModal_2' onclick='openForm3(" + t3 + ")' style='color: #fff;background-color: #398439;border-color: #255625;'>EDIT</button></td></tr><tr><td colspan='6' class='hiddenRow'><div class='accordian-bodyproj collapse' id='demo" + t3 + "'> <table id='tableinvoice_proj' class='tableinvoice_proj' style='border-collapse:collapse;'><thead><tr><th>Invoice Date</th><th>Invoice Number</th><th>Invoice Amount</th><th>Received Amount</th><th>Generate Receipt</th></tr></thead><tbody></tbody></table>";
$("#tableproject").append(tr);
$("#tableproject").append('</div></td></tr>');
}
for (var property in object) {
//alert(object[property].invoice_No);
var t6 = format(object[property].invoice_Date);
var t7 = object[property].invoice_No;
var t8 = object[property].invoice_amount;
var t9 = object[property].received_Amt;
var t10 = object[property].proje_ID; //invoice table's project id
var trtoggle = "<tr><td>" + t6 + "</td><td>" + t7 + "</td><td>" + t8 + "</td><td class=''>" + t9 + "</td><td class=''><input type='checkbox' name='myTextEditBox' value='checked' /> checkbox</td></tr>";
$(".tableinvoice_proj").append(trtoggle);
}
Here is the screenshot
PHP MODAL:
public function list_all_projects_invoice($data) //project section display with ALL Category
{
$array_store = array();
foreach($this->one_allcategory($data) as $row) {
$child = $this->many_allcategory($row['project_ID']);
if($child) {
$return = array_merge(array("parent" => $row), array("child" =>$child));
array_push($array_store, $return);
}
}
return $array_store;
}
public function one_allcategory($data) {
$query = $this->db->select("*")
->where("comp_ID", $data)
->get("project_details")
->result_array();
return $query;
}
public function many_allcategory($id) {
$query = $this->db->select('invoice_No,received_Amt,invoice_amount,proje_ID,invoice_Date')
->where("proje_ID", $id)
->get("invoice_details")
->result_array();
return $query;
}

It's because you append trtoggle to .tableinvoice_proj without specifying the exact element with this class then trtoggle append to all of element with .tableinvoice_proj class.
According to the code you can try
$(".tableinvoice_proj").last().append(trtoggle);
instead of
$(".tableinvoice_proj").append(trtoggle);
new_data = new Object();
new_data.projectinvoicesection = [{
"parent": {
"project_ID": "1",
"project_title": "Network and Telephone Points",
"particulars": "Test Description",
"project_amount": "10000.00",
"type": "One Time",
},
"child": [{
"invoice_No": "1002",
"received_Amt": "0.00",
"invoice_amount": "472.50",
"proje_ID": "1",
"invoice_Date": "2021-08-31"
}]
},
{
"parent": {
"project_ID": "2",
"project_title": "Configuration and Programming",
"particulars": "test description",
"project_amount": "2000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1004",
"received_Amt": "0.00",
"invoice_amount": "245.70",
"proje_ID": "2",
"invoice_Date": "2021-08-30"
}]
},
{
"parent": {
"project_ID": "3",
"project_title": "Coffee ERP",
"particulars": "test",
"project_amount": "50000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1000",
"received_Amt": "0.00",
"invoice_amount": "1820.70",
"proje_ID": "3",
"invoice_Date": "2021-08-19"
},
{
"invoice_No": "1001",
"received_Amt": "0.00",
"invoice_amount": "1773.45",
"proje_ID": "3",
"invoice_Date": "2021-08-24"
}
]
},
{
"parent": {
"project_ID": "6",
"project_title": "sample project new design",
"particulars": "Test Project new",
"project_amount": "4000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1005",
"received_Amt": "0.00",
"invoice_amount": "283.50",
"proje_ID": "6",
"invoice_Date": "2021-08-21"
}]
},
{
"parent": {
"project_ID": "9",
"project_title": "TEST",
"particulars": "NO RESULT",
"project_amount": "0",
"type": "One Time",
"period_type": " ",
},
"child": []
}
]
for (var i = 0; i < new_data.projectinvoicesection.length; i++) {
var sl = i + 1;
//alert(t6)
var t1 = new_data.projectinvoicesection[i]['parent'].project_amount;
//alert(t1)
var t2 = new_data.projectinvoicesection[i]['parent'].particulars;
var t3 = new_data.projectinvoicesection[i]['parent'].project_ID;
var t4 = new_data.projectinvoicesection[i]['parent'].project_title;
var t5 = new_data.projectinvoicesection[i]['parent'].type;
var t56 = new_data.projectinvoicesection[i]['parent'].period_type;
var object = new_data.projectinvoicesection[i]['child'];
var tr = "<tr data-toggle='collapse' data-target='#demo" + t3 + "' style='background-color: #337ab7;color: white;' class='accordion-toggle'><td>" + sl + "</td><td>" + t4 + "</td><td>" + t1 + "</td><td style='white-space: nowrap;'>" + t5 + " " + t56 + "</td><td><button class='open-button-project-edit btn' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#exampleModal_2' onclick='openForm3(" + t3 + ")' style='color: #fff;background-color: #398439;border-color: #255625;'>EDIT</button></td></tr><tr><td colspan='6' class='hiddenRow'><div class='accordian-bodyproj collapse' id='demo" + t3 + "'> <table id='tableinvoice_proj' class='tableinvoice_proj' style='border-collapse:collapse;'><thead><tr><th>Invoice Date</th><th>Invoice Number</th><th>Invoice Amount</th><th>Received Amount</th><th>Generate Receipt</th></tr></thead><tbody></tbody></table>";
$("#tableproject").append(tr);
$("#tableproject").append('</div></td></tr>');
if( !object || object.length < 1)
{
var trtoggle = `<tr ><td style='text-align:center;' colspan='5' > No records found!</td></tr>`;
} else
{
var trtoggle = '';
for ( var property in object ) {
//alert(object[property].invoice_No);
var t6 = object[property].invoice_Date;
var t7 = object[property].invoice_No;
var t8 = object[property].invoice_amount;
var t9 = object[property].received_Amt;
var t10 = object[property].proje_ID; //invoice table's project id
trtoggle += "<tr><td>" + t6 + "</td><td>" + t7 + "</td><td>" + t8 + "</td><td class=''>" + t9 + "</td><td class=''><input type='checkbox' name='myTextEditBox' value='checked' /> checkbox</td></tr>";
}
}
$(".tableinvoice_proj").last().append(trtoggle);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableproject">
</table>

Your second for loop needs to be inside of the first for loop (nested):
//You have
For(){
}
For(){
}
//You need
For(){
For(){
}
}

Related

Not getting the expected results from for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm having trouble with a if statement in a for loop where the items are not fitting under the h1 like i would of expected it's almost like the if is been missed the first go and that messes things up
Here is some example code and the jsfiddle to go with it http://jsfiddle.net/xpvt214o/714036/
var jsonOut = [{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
]
var content = ''
var lastDate = 0
for (var i = 0; i < jsonOut.length; i++) {
var testDate = new Date(jsonOut[i].timestamp * 1000);
var contentNow = ''
var ResultName = ''
var h1marker = ''
for (var j = 0; j < jsonOut[i].check.length; j++) {
ResultName = ResultName + '' + jsonOut[i].check[j].name + '<br>'
contentNow = testDate + '<br>' + ResultName
}
if (jsonOut[i].timestamp != lastDate) {
h1marker = "<h1>" + testDate.getDate() + "</h1>"
lastDate = jsonOut[i].timestamp
}
content = h1marker + contentNow + content
}
$("#tests").html(content)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests">
</div>
There is no problem with your if-statement at all. Your code at this part
content = h1marker + contentNow + content
Puts the new content IN FRONT of the old, therefore your second entry for each date is above the header "30".
Change it to content = content + h1marker + contentNow like in the following snippet:
var jsonOut = [{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
]
var content = ''
var lastDate = 0
for (var i = 0; i < jsonOut.length; i++) {
var testDate = new Date(jsonOut[i].timestamp * 1000);
var contentNow = ''
var ResultName = ''
var h1marker = ''
for (var j = 0; j < jsonOut[i].check.length; j++) {
ResultName = ResultName + '' + jsonOut[i].check[j].name + '<br>'
contentNow = testDate + '<br>' + ResultName
}
if (jsonOut[i].timestamp != lastDate) {
h1marker = "<h1>" + testDate.getDate() + "</h1>"
lastDate = jsonOut[i].timestamp
}
content = content + h1marker + contentNow
}
$("#tests").html(content)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests">
</div>

Jquery multiply input number value and Json data

I have a time calculation tool which you can find in the following fiddle link. Once someone has selected a platform, task type, component and number of units, the number of units entered should be multiplied with selected component value and show it on the below table. I have managed to get the all populated values but can't do the math. I have tried several attempts but it wasn't working.
var myJson = {
"platforms": [
{
"name": "Sitecore",
"id": "sitecore",
"tasktype": [
{
"name": "Promobox",
"id": "promobox",
"components": [
{
"name": "Accordion",
"id": "accordion",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "video",
"components": [
{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "siab",
"tasktype": [
{
"name": "Newswire",
"id": "newswire",
"components": [
{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "tasktypenew",
"components": [
{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function (index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function () {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function (index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function () {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function (index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function () {
$('#calculate').click(function () {
$('#calc input, #calc select').each(
function (index) {
var input = $(this);
$('#data tbody').append('<tr><td>' + input.val() + '</td></tr>');
});
});
});
JS Fiddle
Ok this took a lot of debugging. You were building your table wrong and not storing data properly. The whole fishing for data was problematic. Here is the debugged calculator:
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
console.log(tr);
$('#calc input, #calc select').each( function (index) {
console.log($(this));
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + input.val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
});
});
notice:
Change of table structure format.
Now appending td's to single tr each time in order to sustain table-row consistency.
Fishing data from row with the help of adding class tag identifier to each td
Showing result.
update fiddle link:
https://jsfiddle.net/x4rLuf88/1/

How to call json file data in my html file ? below is my json file structure

[
{
"id": 2,
"name": "An ice sculpture",
"price": 12.50,
},
{
"id": 3,
"name": "A blue mouse",
"price": 25.50,
}
]
Json object :
var data = [
{
"id": 2,
"name": "An ice sculpture",
"price": 12.50
},
{
"id": 3,
"name": "A blue mouse",
"price": 25.50
}
];
Iterate every property of the object :
var htmlContent = '';
for ( var key in data ) {
htmlContent += '<div class="container">';
htmlContent += '<p> Name: ' + data[key].name + '</p>';
htmlContent += '<p> Price: ' + data[key].ptice + '</p>';
htmlContent += '</div>';
}
$('body').append(htmlContent);
$url= " http://nominatim.openstreetmap.org/reverseformat=json&lat=12.9166&lon=77.6101&zoom=18&addressdetails=1";
$json = #file_get_contents($url); $data = json_decode($json);
How to receive data from this link.

String not being appended in function

I am trying to parse a JSON and build a HTML string to append to the DOM but no matter what I do the string is only returning the first element in the JSON.
Here's the js:
var menu_json = {
"name": "Personal Banking",
"url": "/test1.html",
"children": [
{
"id": "1",
"name": "test2",
"url": "/products/deposits/test2.html",
"children": [
{
"id": "1",
"name": "test3",
"url": "/products/deposits/test3.html",
"children": [
{
"id": "1",
"name": "test5",
"url": "test5"
},
{
"id": "2",
"name": "test6",
"url": "/products/deposits/test6.html"
},
{
"id": "3",
"name": "test7",
"url": "/products/deposits/test7.html"
},
{
"id": "4",
"name": "test8",
"url": "/products/deposits/test8.html"
},
{
"id": "5",
"name": "test9",
"url": "/products/deposits/test9.html"
},
{
"id": "6",
"name": "test10",
"url": "/products/deposits/test10.html"
},
{
"id": "7",
"name": "test11",
"url": "/products/deposits/test11.html"
}
]
}
]
}
]
}
var test_html = "<ul>",
buildNavHelper = function(curNode){
test_html += "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper) + "</ul>";
}
test_html += "</li>";
};
buildNavHelper(menu_json);
test_html += "</ul>";
$('#thing').append(test_html);
Heres a fiddle
https://jsfiddle.net/w734bvw7/
buildNavHelper() has no return statement, so there's nothing coming back from _.map(). The outer test_html isn't in scope. Try this:
buildNavHelper = function(curNode){
var test_html = "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper).join("") + "</ul>";
}
test_html += "</li>";
return test_html;
};
test_html = "<ul>" + buildNavHelper(menu_json) + "</ul>";
Note the addition of .join() to avoid having commas in your output.
Also, there's no need to use underscore here; Array.map() is native Javascript.
buildNavHelper = function(curNode){
var test_html = "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + curNode.children.map(buildNavHelper).join("") + "</ul>";
}
test_html += "</li>";
return test_html;
};
https://jsfiddle.net/w734bvw7/3/
buildNavHelper = function(curNode){
var test_html = "<ul>";
test_html += "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper) + "</ul>";
}
test_html += "</li>";
test_html += "</ul>";
return test_html;
};
$('#thing').append(buildNavHelper(menu_json));
Building the list using HTML strings can produce HTML injection. I recommend DOM methods instead:
function buildNavHelper(arr) {
var ul = document.createElement('ul');
for(var i=0; i<arr.length; ++i) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(arr[i].name));
if(arr[i].children)
li.appendChild(buildNavHelper(arr[i].children));
ul.appendChild(li);
}
return ul;
}
var menu_json = {
"name": "Personal Banking",
"url": "/test1.html",
"children": [
{
"id": "1",
"name": "test2",
"url": "/products/deposits/test2.html",
"children": [
{
"id": "1",
"name": "test3",
"url": "/products/deposits/test3.html",
"children": [
{
"id": "1",
"name": "test5",
"url": "test5"
},
{
"id": "2",
"name": "test6",
"url": "/products/deposits/test6.html"
},
{
"id": "3",
"name": "test7",
"url": "/products/deposits/test7.html"
},
{
"id": "4",
"name": "test8",
"url": "/products/deposits/test8.html"
},
{
"id": "5",
"name": "test9",
"url": "/products/deposits/test9.html"
},
{
"id": "6",
"name": "test10",
"url": "/products/deposits/test10.html"
},
{
"id": "7",
"name": "test11",
"url": "/products/deposits/test11.html"
}
]
}
]
}
]
}
function buildNavHelper(arr) {
var ul = document.createElement('ul');
for(var i=0; i<arr.length; ++i) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(arr[i].name));
if(arr[i].children)
li.appendChild(buildNavHelper(arr[i].children));
ul.appendChild(li);
}
return ul;
}
document.querySelector('#thing').appendChild(buildNavHelper([menu_json]));
<div id="thing"></div>

How to access nested value from JSON Instagram API with Javascript

Im trying to modify script from https://github.com/bigflannel/bigflannel-Instafeed to access Instagram Photos in Website. But it doesn't include feature to display photo comments. So, im trying to modify but it returns undefined value. The script uses javascript to access data from API.
Example:
[
{
"attribution": null,
"tags": [
],
"type": "image",
"location": null,
"comments": {
"count": 2,
"data": [
{
"created_time": "1389168592",
"text": "Beautiful bridge!",
"from": {
"username": "realwahyuputra",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/profile_180213154_75sq_1359089013.jpg",
"id": "180213154",
"full_name": "realwahyuputra"
},
"id": "628714182443349004"
},
{
"created_time": "1389168601",
"text": "also good views",
"from": {
"username": "realwahyuputra",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/profile_180213154_75sq_1359089013.jpg",
"id": "180213154",
"full_name": "realwahyuputra"
},
"id": "628714254652486672"
}
]
},
"filter": "Hefe",
"created_time": "1350749506",
"link": "http:\/\/instagram.com\/p\/RAqdlGyTSc\/",
"likes": {
"count": 0,
"data": [
]
},
"images": {
"low_resolution": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_7.jpg",
"width": 612,
"height": 612
}
},
"users_in_photo": [
],
"caption": {
"created_time": "1350749545",
"text": "From the office",
"from": {
"username": "bigflannel",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/anonymousUser.jpg",
"id": "240129684",
"full_name": "Mike Hartley"
},
"id": "306431853609956969"
},
"user_has_liked": false,
"id": "306431525321782428_240129684",
"user": {
"username": "bigflannel",
"website": "",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/anonymousUser.jpg",
"full_name": "Mike Hartley",
"bio": "",
"id": "240129684"
}
}];
Here's one of function to access data from that JSON:
function imageCaptionText(timestamp) {
var text = 'Filter: ' + imageData[imageCount].filter + '<br />'
if (imageData[imageCount].caption != null) {
text = text + 'Caption: ' + imageData[imageCount].caption.text + '<br />';
}
if (imageData[imageCount].likes.count > 0) {
text = text + 'Likes: ' + imageData[imageCount].likes.count + '<br />';
}
if (imageData[imageCount].comments.count > 0) {
text = text + 'Comments: ' + imageData[imageCount].comments.count + '<br />';
}
if (imageData[imageCount].comments.data != null) {
text = text + 'Comments Data: ' + imageData[imageCount].comments.data.text + '<br />';
}
if (imageData[imageCount].location != null) {
text = text + 'Location: ' + imageData[imageCount].location + '<br />';
}
var date = new Date(1000*timestamp);
text = text + 'Date: ' + date.toLocaleString() + '<br />';
text = text + 'On Instagram<br />';
return text; }
Everything goes fine except this code returns undefined value (I'm trying to create this to access comments data)
if (imageData[imageCount].comments.data != null) {
text = text + 'Comments Data: ' + imageData[imageCount].comments.data.text + '<br />';
}
How to make it works? Any help would be appreciated. Thanks :)
comments.data is an array, the actual text will be at imageData[imageCount].comments.data[commentCount].text so you have to do something like this:
if (imageData[imageCount].comments.data != null) {
text = 'Comments Data:<br />';
imageData[imageCount].comments.data.forEach(function(comment){
text += comment.from.username + ': ' + comment.text + '<br />';
});
}

Categories

Resources