Im trying to get value from an array:
[
{
"id": "5899aaa321e01b8b050041cb",
"name": "John Doe",
"picture": {"small": "https://cdn.image.com/1234"},
"age": 28,
"location": {"city": "London"},
"following": 1,
"resources": {"band": "http://image/music"},
"top_works": [
{
"points": 20,
"portfolio": {
"facebook_id": "1e691681472",
"picture": {"small": "https://cdn.image.com/1234"}
}
},
{
"points": 10,
"portfolio": {
"facebook_id": "1e6916r17ry",
"picture": {"small": "https://cdn.image.com/1234"}
}
}
]
}
]
$(document).ready(function() {
$.ajax({
type: 'GET',
url: '/api/url/123',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function (index, element) {
$('#api').append('<div>'
+ ' <div><h3>' + element.name + '</h3></div>'
+ '<div>' + element.top_works[2].portfolio.picture.small + '></div>');
});
}
});
});
I can read without problem all, neither the "top_works, because i need to specific the number [x], and I need a loop.
In some case if the top_works is empty i get an "undefined in console", i need to show a white space if the element does'nt exsist.
Someone can help me?
You should verify if that exists, something like:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
var exists = element.top_works[2] && element.top_works[2].portfolio && element.top_works[2].portfolio.picture && element.top_works[2].portfolio.picture.small;
HTML+= exists ? '<div>' + element.top_works[2].portfolio.picture.small + '</div>' : '<div>#empty space</div>';
$('#api').append(HTML + '</div>');
});
But if you want to search for a picture on the last index, maybe you can do this:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
var last = element.top_works ? element.top_works.length-1 : -1;
var exists = last >= 0;
HTML+= exists ? '<div>' + element.top_works[last].portfolio.picture.small + '</div>' : '<div>#empty space</div>';
$('#api').append(HTML + '</div>');
});
EDIT
For a loop, you can do this:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
if(element.top_works && element.top_works.length > 0) {
for(var i in element.top_works) {
HTML+= '<div>' + element.top_works[i].portfolio.picture.small + '</div>';
}
} else {
HTML += '<div>#empty space</div>';
}
$('#api').append(HTML + '</div>');
});
you can make use of array.length property to check if and element exists or not as shown in following example.
var topWorks = { "top_works": [
{
"points": 20,
"portfolio": {
"facebook_id": "1e691681472",
"picture": {
"small": "https://cdn.image.com/1234",
}
}
},
{
"points": 10,
"portfolio": {
"facebook_id": "1e6916r17ry",
"picture": {
"small": "https://cdn.image.com/1234",
}
}
},
]
}
if(topWorks.top_works.length > 0) {
console.log("Top works has element at index 0");
}
if(topWorks.top_works.length > 1) {
console.log("Top works has element at index 1");
}
if(topWorks.top_works.length > 2) {
console.log("Top works has element at index 2");
}else
{
console.log("Top works does not have element at index 2");
}
Related
This jQuery code parse json data and create html table to div:
$(document).ready(function () {
const jsonData = $.getJSON("js/quotes.json");
function quotes(a, b) {
(this.$div = $(a)),
(this._quotes = b),
(this._init = function () {
var a = this;
jsonData.then(function (b) {
if ("object" != typeof b) return !1;
var c = [];
a._quotes.forEach(function (a) {
(a = a.trim()),
b[a] &&
c.push(
'<tr data-name="' + b[a].code + '" class="' + b[a].movement + '"><td>' +
b[a].code +
'</td><td>' +
b[a].bid +
'</td><td>' +
b[a].ask +
'</td><td>' +
b[a].spread +
"</td></tr>"
);
}),
c.length > 0 && a.$div.html("<table><tr><th>Symbol</th><th>Bid</th><th>Ask</th><th>Spread</th></tr>" + c.join("") + "</table>"),
setTimeout(a._init, 50e3);
});
}),
this._init();
}
quotes("#quotes-block1", $("#quotes-block1").data("quotes1").split(","));
quotes("#quotes-block2", $("#quotes-block2").data("quotes2").split(","));
});
HTML code:
<div id="quotes-block1" data-quotes1="EUR/USD, GBP/USD, USD/CHF, USD/JPY"></div>
<div id="quotes-block2" data-quotes2="XRP/USD, LTC/USD"></div>
Json:
"XRP\/USD": {
"bid": 0.5676,
"ask": 0.5698,
"type": "Cryptos",
"code": "XRP\/USD",
"mid": 0.5687,
"movement": "down",
"spread": 0.0022
},
"LTC\/USD": {
"bid": 82.89,
"ask": 83.72,
"type": "Cryptos",
"code": "LTC\/USD",
"mid": 83.305,
"movement": "down",
"spread": 0.83
},
"ETH\/USD": {
"bid": 588.62,
"ask": 589.63,
"type": "Cryptos",
"code": "ETH\/USD",
"mid": 589.125,
"movement": "up",
"spread": 1.01
},
etc.
I need create table in div id="quotes-block1" and id="quotes-block2", but work only div id="quotes-block2"
What is my mistake? Help!
Live example:
json file: http://maxbeaub.bget.ru/json/js/quotes.json
jquery function: http://maxbeaub.bget.ru/json/js/quotes.js (get data from json and append table to div)
html result: http://maxbeaub.bget.ru/json/json.html (append table only to second div)
The reason being is content being overwritten in second div only get referenced in an a.
function quotes(a, b) {
(this.$div = $(a)),
(this._quotes = b),
(this._init = function (div) {
var a = this;
jsonData.then(function (b) {
if ("object" != typeof b) return !1;
var c = [];
a._quotes.forEach(function (a) {
(a = a.trim()),
b[a] &&
c.push(
'<tr data-name="' + b[a].code + '" class="' + b[a].movement + '"><td>' +
b[a].code +
'</td><td>' +
b[a].bid +
'</td><td>' +
b[a].ask +
'</td><td>' +
b[a].spread +
"</td></tr>"
);
}),
c.length > 0 && div.html("<table><tr><th>Symbol</th><th>Bid</th><th>Ask</th><th>Spread</th></tr>" + c.join("") + "</table>"),
setTimeout(a._init, 5e3);
});
}),
this._init(this.$div);
I currently have a json file of people taking part in a series of charity events in the following format:
[
{
"FirstName": "Anushka",
"Country": "UK",
"Day": "13/10/2017"
},
{
"FirstName": "Alessandra",
"Country": "IT",
"Day": "16/10/2017"
},
{
"FirstName": "Clare",
"Country": "US",
"Day": "13/10/2017"
}
]
I want to build a simple HTML list using this data, so that under each date, the name and country are displayed like:
<div id="13102017">
<h1>13/10/2017</h1>
<div class="col-sm-4"><p>Anushka, UK</p></div>
<div class="col-sm-4"><p>Clare, US</p></div>
</div>
<div id="16102017">
<h1>16/10/2017</h1>
<div class="col-sm-4"><p>Alessandra, IT</p></div>
</div>
I've new to JSON and so far I have figured out how to get Name and Country onto the page, but I cannot figure out how to use an if statement to only output if date = 13/10/2017 for example.
Here's what I've got so far:
$( document ).ready(function() {
$.getJSON("URL_HERE", function(data) {
$.each(data, function(i, item) {
$('#13102017').append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
});
});
});
Obviously the above is currently just outputting every single name into the #13102017 section. I know I probably need an IF in there somewhere but I'm otherwise stumped. Any pointers would be much appreciated!
On each loop, check first if the date div exists, and if not, create it. Then append the info to that div...
$.getJSON("URL_HERE",function(data) {
$.each(data, function(i,item) {
var dateId = item.Day.replace(/\//g,'');
if (!$('div#'+dateId).length)
$('body').append('<div id="'+dateId+'"><h1>'+item.Day+'</h1></div>');
$('div#'+dateId).append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
});
});
For array loops, I personally prefer to use for (is faster than jquery each)...
$.getJSON("URL_HERE",function(data) {
for (var i=0, l=data.length; i<l; i++) {
var item = data[i],
dateId = item.Day.replace(/\//g,'');
if (!$('div#'+dateId).length)
$('body').append('<div id="'+dateId+'"><h1>'+item.Day+'</h1></div>');
$('div#'+dateId).append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
}
});
NOTE: I'm adding the date div's to the body, just change $('body') to the container where you want to put them in your page.
I would suggest you to create the whole html and then set it as html.
var data = [{
"FirstName": "Anushka",
"Country": "UK",
"Day": "13/10/2017"
},
{
"FirstName": "Alessandra",
"Country": "IT",
"Day": "16/10/2017"
},
{
"FirstName": "Clare",
"Country": "US",
"Day": "13/10/2017"
}
];
$(function() {
// You can have this inside $.getJSON
var _html = "";
data.forEach(function(item) {
_html += '<div id="' + item.Day.replace(/\//g, "") + '">' +
'<h1>' + item.Day + '</h1>' +
'<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>' +
'</div>';
});
$("#container").html(_html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
but I cannot figure out how to use an if statement to only output if
date = 13/10/2017
Simply check if item.Day == "13102017"
$( document ).ready(function() {
$.getJSON("URL_HERE", function(data) {
$.each(data, function(i, item) {
if ( item.Day == "13102017" )
{
var id = item.Day.replace( /\D/g, "" );
var html = '<div id="' id '">';
html += '<h1>' + item.Day + '</h1>';
html += '<div class="col-sm-4"><p>' + item.FirstName + '</p></div>';
html += '<div class="col-sm-4"><p>' + item.Country + '</p></div>';
html += '</div>';
$(body).append( html );
}
});
});
});
i need to edit nested objects with unique key's! in couhdb document, but i can't do it.
my doc structure:
{
"_id":"20",
"_rev":"rev",
tasks": {
"20.t01": {
"name": "test",
"status": [],
"tasks": {
"20.t01t01": {
"status": [
],
"name": "name",
"tasks": {
"20.t01t01t01": {
"status": [],
"name": "name",
"tasks": {
"20.t01t01t01t01": {
"name": "name",
"status": [],
"tasks": {
}
}
}
}
}
}
}
}
}
}
I nedd to push some objects into status array's.
The update handler function:
"status": function(doc, req) {
var data = JSON.parse(req.body);
var value = data.value;
var path = data.path;
var message = 'set ' + path + ' status ' + value;
var pathar = path.split(".");
var level;
var body = doc;
var evalstr = "body.";
if (pathar[1].length > 2) {
level = (pathar[1].length) / 3;
for (var i = 1; i <= level - 1; i++) {
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1].substring(0, i * 3) + "\"].";
}
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1] + "\"].status.push(" + JSON.stringify(value) + ");";
} else {
level = 1;
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1] + "\"].status.push(" + JSON.stringify(value) + ");";
}
eval([evalstr]);
doc = body;
//doc.tasks["20.t01"].tasks["20.t01t01"].status.push(value);
return [doc, JSON.stringify({
reg: evalstr,
doc: body
})];
}
how i write the design document update function for this structure in couchdb?
Tanks!
I al using javascript and looping through the values of a submitted form and trying to build a son object out of the form values.
This is an example of the final object I need:
{
"DataObject": {
"user": { "-name": "username" },
"contentFile": {
"-filename": "Breaking_News",
"lock": { "-fileIsBeingEdited": "false" },
"content": {
"line": [
{
"-index": "1",
"-text": "this is the header"
},
{
"-index": "2",
"-text": "this is the first line"
},
{
"-index": "3",
"-text": "this is the second line"
}
]
}
}
}
}
So far i am adding all of this data to a string as that seems to be the only way i can insert the form values (the line array) into the middle of the object.
var jsonStr = '{'
+ 'iceteaDataObject: {'
+ 'user: {"-name": "hindsc52"},'
+ 'contentFile: {'
+ '"-filename": "Ticker",'
+ 'lock: { "-fileIsBeingEdited": "false" },'
+ 'content: {'
+ 'line: ['
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
jsonStr += '{'
jsonStr += "-index: " + i + ',';
jsonStr += "-text: " + elem[i].value;
jsonStr += '},'
}
}
jsonStr += ']}}}}';
console.log(JSON.parse(jsonData));
however when running this I get the error: unexpected token 'i'.
I have tried to use stringily but then just outputs the entire sting again.
You don't need or want JSON for this, just build the object:
// Sample data
var elem = [{
value: "one"
}, {
value: "two"
}];
// Build the object
var obj = {
"DataObject": {
"user": {
"-name": "username"
},
"contentFile": {
"-filename": "Breaking_News",
"lock": {
"-fileIsBeingEdited": "false"
},
"content": {
"line": []
}
}
}
};
var line = obj.DataObject.contentFile.content.line;
elem.forEach(function(entry, index) {
if (entry.value != '') {
line.push({
"-index": index,
"-text": entry.value
});
}
});
// Show result:
document.body.innerHTML =
"<pre>" +
JSON.stringify(obj, null, 2) +
"</pre>";
Side note: You don't check for blank strings like this:
if (!entry.value == '') { // <== Incorrect
You can use:
if (entry.value != '') {
or:
if (entry.value) {
You shouldn't build JSON like this, but use JSON.stringify() (see MDN doc) instead:
var myObject={foo:"bar"};
var myJSON=JSON.stringify(myObject);
console.log(myJSON); //echo {"foo":"bar"}
Here is an alternative way:
var json = {
iceteaDataObject: {
"-name": "hindsc52"
},
contentFile: {
"-filename": "Ticker",
lock: { "-fileIsBeingEdited": "false" },
content: {line: []}
}
}
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
json.contentFile.content.line.push({"-index": i,"-text": elem[i].value }
}
}
var jsonStr = JSON.stringify(json);
You need to put all your keys in quotes for this to work. As the others have pointed out though, you are not really supposed to do this.
If you still want to do it your way, try this:
var jsonStr = '{'
+ '"iceteaDataObject": {'
+ '"user": {"-name": "hindsc52"},'
+ '"contentFile": {'
+ '"-filename": "Ticker",'
+ '"lock": { "-fileIsBeingEdited": "false" },'
+ '"content": {'
+ '"line": ['
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
jsonStr += '{'
jsonStr += '"-index": ' + i + ',';
jsonStr += '"-text": ' + '"' + elem[i].value + '"';
jsonStr += '},'
}
}
jsonStr += ']}}}}';
I have a ajax returning data some times like
{
"results": [{
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}]
}
for above my forEach function is working fine but when same data is returning
{
"results": {
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}
}
my forEach function not working
$.get(url, function(data){
var x =data['results'];
x.forEach(function logArrayElements(element, index, array) {
$(self).append('<button class="tag-format" title="'+array[index].Name+'" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> '+ array[index].symbol +" - "+ array[index].PriceSales +' </button>');
});
});
That's because your JSON isn't an array. You can easily check beforehand using Array.isArray(). You should also be using getJSON if the data you are retrieving is in fact JSON.
$.getJSON(url, function(data) {
var x = data.results;
if(Array.isArray(x)) {
x.forEach(function logArrayElements(element, index, array) {
$(self).append('<button class="tag-format" title="' + array[index].Name + '" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> ' + array[index].symbol + " - " + array[index].PriceSales + ' </button>');
});
} else {
$(self).append('<button class="tag-format" title="' + x.Name + '" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> ' + x.symbol + " - " + x.PriceSales + ' </button>');
}
});
Your forEach is for iterating over an array. In your second JSON, there is no array to iterate over, so you need to call the function directly on data['results']:
$.get(url, function(data){
var x = data['results'],
addButton = function(item) {
$(self).append('<button class="tag-format" title="'+array[index].Name+'" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> '+ array[index].symbol +" - "+ array[index].PriceSales +' </button>');
};
if(Array.isArray(x)) {
x.forEach(function logArrayElements(element, index, array) {
addButton(array[index]);
});
} else {
addButton(x);
}
});
Javascript object is not an Array.
Html
<div id="results"></div>
Javascript
var firstArray = {
"results": [{
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}]};
var secondArray = {
"results": {
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}};
//Result: 1
$("#results").append("<span>FirstArray result: " + firstArray['results'].length + "</span><br/>");
//Result: undefined
$("#results").append("<span>FirstArray result: " + secondArray['results'].length + "</span><br/>");