How to read object string using jquery? - javascript

I am getting this object value as string
'{gallery: 'gal', smallimage: 'http://www.website.com/image.jpg',largeimage: 'http://www.website.com/image1.jpg'}'
How can i read this using jquery? Currently i am using this following function as bellow to read this but i can't find value in $each
$(".jcarousel-item a").click(function() {
alert($(this).attr("rel"));//I can find this object value here
$.each($(this).attr("rel"), function(index, value) {
alert(index + ': ' + value);
});
});

You do not have to depend on jQuery for this:
var i;
var array =$(this).attr("rel");
for (i = 0; i < array.length; ++i) {
// do something with `array[i]`
}

Try to parse the array as this:
$(".jcarousel-item a").click(function() {
var arrayData = $(this).attr("rel");
var objData = JSON.parse(arrayData);
// Here objData is a JSON, you can access how this
alert(objData.gallery);
alert(objData.smallimage);
alert(objData.largeimage);
});

Related

How to find JSON data at specific index

I want to show only the country name like India,Srilanka etc.
{"result":1,"countries":[
{"country_id":"1","country_name":"Afghanistan"},
{"country_id":"2","country_name":"Albania"},
{"country_id":"3","country_name":"Algeria"},
{"country_id":"4","country_name":"American Samoa"},
{"country_id":"5","country_name":"Andorra"},
{"country_id":"6","country_name":"Angola"},
{"country_id":"7","country_name":"Anguilla"}
]
}
Below I have created JSON object same as yours:
var text = '{"result":1,"countries":[' +
'{"country_id":"1","country_name":"Afghanistan"},' +
'{"country_id":"2","country_name":"Albania"},' +
'{"country_id":"3","country_name":"Algeria"}'+
']}';
var obj = JSON.parse(text);
you can loop through JSON object and get each property value as below:
for(i = 0; i < obj.countries.length ; i++)
{
console.log(obj.countries[i].country_name);
}
Hope This Will Help!
why no iterate the objects and pull that data into a separate array? for example:
[[{"country_id":"1","country_name":"Afghanistan"},{"country_id":"2","country_name":"Albania"},{"country_id":"3","country_name":"Algeria"},{"country_id":"4","country_name":"American Samoa"},{"country_id":"5","country_name":"Andorra"},{"country_id":"6","country_name":"Angola"},{"country_id":"7","country_name":"Anguilla"}]]
.forEach(function(element) {
console.log(element.country_name);
});

Access data from Object in json response

My json returns below shown set of array of objects and I need to access the data inside it. In the console this is what the response looks like
What i am trying to do is to access the object to get the subcategoryid and subcategoryname then display it inside a dropdown list. Here is my code for it
$.get('ajax-subcat?cat_id=' + cat_id, function(data)
{
console.log(data);
$('#subcategory').empty();
$.each(data, function(index, subcatObj)
{
alert(subcatObj);
$('#subcategory').append('<option value="' + subcatObj.Object.subcategoryid +'">' + subcatObj.subcategoryname +'</option>');
});
});
The thing I don't know is how to access the data inside the object. Any ideas?
Try this:
JAVASCRIPT
for (var i = 0; i < data.length; i++) {
console.log(data[i].subcategoryid);
}
Assuming that you have a select element in markup:
<select id="mySelectElement"></select>
Try this to iterate the object and fill the combo box:
$.get('ajax-subcat?cat_id=' + cat_id, function(data) {
// Get a reference to the target element
var selectTarget = $('#mySelectElement');
// Iterate over the response data
for (var i in data) {
// For every object in array, append a new option element
selectTarget.append($('<option value="' + data[i].subcategoryid + '">' + data[i].subcategoryname + '</option>'));
}
});
For this purpose, you can use underscore.js library to get whole data corresponding to particular key in the form of array.
_.pluck(data, 'subCategoryid') // array of all values corresponding to 'subcategoryid'

How to insert a json object into an unordered list

I have a json object that i created using obj = JSON.parse(data). "data" was recieved from a webserver. I know the object is correct because i can print single variables from it into a div or my list.
This is what is the json object is created from:
[{"name":"Staurikosaurus","group":"Saurischia","diet":"Carnivore","period":"Triassic"},{"name":"Diplodocus","group":"Saurischia","diet":"Herbivore","period":"Jurassic"},{"name":"Stegosaurus","group":"Ornithischia","diet":"Herbivore","period":"Jurassic"},{"name":"Tyrannosaurus","group":"Saurischia","diet":"Carnivore","period":"Cretaceous"}]
Literally all i want to do is put this into a to show up on a web page.
My current code:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
$('#myList').html("<li>"+obj[0].period+"</li><li>"+obj[2].period+"</li>");
//$('#myList').html("<li>obj[2].period</li>");
});
}
This successfully prints out the list with Triassic then Jurrasic.
I would prefer to do this in Jquery but javascript is okay.
Thank You.
You are not iterating through the list, just printing out the 0-th and 2nd element in the array. Try:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
var inner = '';
for(i=0; i < obj.length; i++) {
inner += "<li>"+obj[i].period+"</li>";
}
$('#myList').html(inner);
});
}
I'm sure there's a cleaner way using jQuery but that should work
If you're want to use the jQuery syntax, process like this:
var listElement = '';
$.each(obj, function(index, value) {
listElement += '<li>' + data[obj].period + '</li>';
})
$('#myList').html(listElement);

what is the right way to set input fields and labels from the properties of the same object in jquery?

I have an object with a bunch of properties. Some properties are to be displayed in input elements, some in labels.
So, my code looks like this:
var data = getMyData();
var propNames = Object.keys(data);
var i, propName, elem;
for (i = 0; i < propNames.length; ++i) {
propName = propNames[i];
elem = $("#" + propName);
if (elem.is('input')) {
elem.val(data[propName]);
} else {
elem.html(data[propName]);
}
}
Is it the right way to do it in jquery? Cause it looks kinda ugly...
Thanks.
I find it easier to store the method name in a variable (text/val), so that we don't have so much code repetition (the conditional in your code makes for unnecessary repetition).
Also, since you're anyhow using jQuery, you might as well use each. It simplifies all of it into this:
$.each(getMyData(), function (key, val)
{
var el = $("#" + key),
method = el.is('input') ? 'val' : 'text';
el[method](val);
});
Here's the fiddle: http://jsfiddle.net/pFbSf/
If you don't like storing the method name in a variable, use this instead:
$.each(getMyData(), function (key, val)
{
var el = $("#" + key);
el.is('input') ? el.val(val) : el.text(val);
});
Here's the fiddle: http://jsfiddle.net/GQTZv/
If you worry about jQuery not using hasOwnProperty, you can run the check yourself:
var data = getMyData();
$.each(data, function (key, val)
{
if ( ! data.hasOwnProperty(key) ) return;
var el = $("#" + key);
el.is('input') ? el.val(val) : el.text(val);
});
Here's the fiddle: http://jsfiddle.net/GQTZv/1/
I think you can rewrite that for-loop with the jQuery .each() function, which can iterate over any array or object. It takes a callback function, which is given the index (or key) and the value of each item.
In your example it would be something like:
jQuery.each(data, function(key, value) {
elem = jQuery("#" + value);
if (elem.is('input')) {...
Check out the docs for jQuery.each()
Assuming you're trying to fill either an input or a textarea, you should be able to replace this with:
var data = getMyData();
var propNames = Object.keys(data);
for (i = 0; i < propNames.length; ++i) {
$("input#"+propNames[i]).val(data[propNames[i]);
$("textarea#"+propNames[i]).html(data[propNames[i]);
}
You might even get away with replacing the two jQuery selectors with:
$("input#"+propNames[i]).val(data[propNames[i]).html(data[propNames[i]);
Since input elements don't have innerHTML and textarea elements don't have val, this should work as-is. Hackish, but it's succinct.
I don't see how that looks ugly but I don't understand why you need Object.keys... You can simplify it a bit with a regular for...in:
var data = getMyData(),
d, $el;
for (d in data) {
$el = $('#'+ d);
if ($el.is('input')) {
$el.val(data[d]);
} else {
$el.html(data[d]);
}
}
Everything looks fine to me Mark. The one thing I would highly advise against is using a new Object prototype method like Object.keys, which is only available in IE9+ and other newer browsers. Instead either create the prototype for it before all of your JS (something I actually don't like doing) or instead have a replica work-around global function / namespace method that takes care of it like function getkeys() at the bottom.
http://jsfiddle.net/WJ24q/1/
for (i = 0; i < propNames.length; ++i) {
var el = $("#" + propNames[i]),
_d = data[propNames[i]];
// you could also use a simple ternary instead of the if/else
el.is('input') ? el.val(_d) : el.html(_d);
}
Function instead of Object.keys:
function getKeys (obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
​ ​

jquery: adding custom key value to object

whats wrong with this jquery code. it is not outputting anyting?
var imagesToLoad = [];
var name = 'hi';
var src = 'ho';
imagesToLoad[name] = src;
$.each(imagesToLoad, function(index, value) {
alert(index + ': ' + value);
});
basically i want to add custom variables to my object after it has been created.
Javascript arrays don't support non numerical indexes. You probably want to use an object instead:
var imagesToLoad = {};
imagesToLoad.hi = 'ho';
$.each(imagesToLoad, function(index, value) {
alert(index + ': ' + value);
});
You should check the doc for $.each method - it accepts only callback function as parameter and it can iterate only over jQuery object

Categories

Resources