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/>");
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);
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");
}
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 += ']}}}}';
This is basically something that makes zero logical sense, and I'm not sure why this is happening.
When you create a function to compare attribute values of an array of objects (essentially JSON object), it refuses to find the index. However, OUTSIDE the function, it seems to work perfectly fine.
However, the problem is
var peoples = [
{ "name": 44, "dinner": "pizza" },
{ "name": 65, "dinner": "sushi" },
{ "name": 33, "dinner": "hummus" }
];
var val = 33;
$("#t").append(get_index_of_array_based_on_value(peoples, val));
function get_index_of_array_based_on_value(array, val) {
$.each(array, function (index, obj) {
$.each(obj, function (attr, value) {
console.log(" attr: " + attr + " == " + value + " (" + val + ") {{" + index + "}} ");
if (value == val) {
return index;
}
});
});
}
http://jsfiddle.net/QStkd/2327/
The above does not work.
The below script does work.
http://jsfiddle.net/QStkd/2330/
The below script is simply the same script except outside the function. When you put stuff into functions it suddenly refuses to find the index based on the value.
You cannot return a value from a $.each call. You are inside a callback, your return doesn't affect the main function.
When you use return inside the $.each callback, it's similar to break/continue in a for/while loop. A falsy value will break the loop, and a truthy value is like calling continue.
You need to return from the main function, get_index_of_array_based_on_value, not from the $.each.
function get_index_of_array_based_on_value(array, val) {
var returnVal = null;
$.each(array, function (index, obj) {
$.each(obj, function (attr, value) {
console.log(" attr: " + attr + " == " + value + " (" + val + ") {{" + index + "}} ");
if (value == val) {
returnVal = index;
return false; // break;
}
});
if(returnVal !== null){
return false; // break the outer loop
}
});
return returnVal;
}
thy this
var peoples = [
{ "name": 44, "dinner": "pizza" },
{ "name": 65, "dinner": "sushi" },
{ "name": 33, "dinner": "hummus" }
];
var val = 33;
$("#t").append(get_index_of_array_based_on_value(peoples, val));
function get_index_of_array_based_on_value(array, val) {
for(var index = 0; index < array.length; index++){
for(var attr in array[index]) {
var value = array[index][attr];
console.log(" attr: " + attr + " == " + value + " (" + val + ") {{" + index + "}} ");
if (value == val) {
return index;
}
}
}
}
I have the following array
array = [
{
"id": "67",
"sub": [
{
"id": "663",
},
{
"id": "435",
}
]
},
{
"id": "546",
"sub": [
{
"id": "23",
"sub": [
{
"id": "4",
}
]
},
{
"id": "71"
}
]
}
]
I am currently looping throught the array as follows
calling the array:
processArray(array);
the function loop
function processArray(arr)
{
for(var item in arr) {
var value = arr[item];
var order = item;
var itemID = value.id;
if(itemID != null)
{
$('.text').append(" ORDER : " + order + " Item ID : " + itemID + "<br />" );
}
if(typeof(value) == 'object') { //If it is an array,
processArray(arr[item]);
}
}
}
Currently i am getting the order of the item and the current ID no problem. What i need however (for my database schema) is for each item get the ID of its parent if there is one.
Do i need to pass the parent to each node? Or is there an easier way?
Thanks
Working demo
Include an optional parameter parentID in the function; by doing this, you can still use the processArray(array); syntax to process the original array.
function processArray(arr, parentID)
{
for(var item in arr) {
var value = arr[item];
var order = item;
var itemID = value.id;
if(itemID != null)
{
var output = " ORDER : " + order + " Item ID : " + itemID;
if( parentID ) { output += " PARENT : " + parentID; }
$('.text').append( output + "<br />");
}
// PROCESS SUB-ARRAY
if( typeof(value.sub) == 'object') { //If it is an array,
processArray( value.sub, itemID );
}
}
}
Use an auxiliary function that has id as part of its signature:
function processArray(arr) {
function _processArray(arr, id) {
for (var item in arr) {
var value = arr[item];
var order = item;
var itemID = value.id; // you need to change this because on the second call you pass in a string and not just an object
var parentId = id;
// Commenting the if statement that you had here actually shows the parent id's now.
$('.text').append(" ORDER : " + order + " Item ID : " + itemID + " Parent Id : " + parentId + "<br />");
if (typeof value === "object") { //use instanceof,
_processArray(arr[item], itemID);
}
}
}
_processArray(arr, 0);
}