How can I display object content without specifying the attributes ? (The object here is used as associative array)
alert(result[0].name);
alert(result[0].surname);
I actually would like to not have to write "name" and "surname", but display all the content (keys & values)
thanks
Try this.. (it uses for each loop):
var arr=[];
arr[0] = 'Test1';
arr['SomeKey'] = 'Test2';
for(var o in arr)
{
var val = arr[o];
alert("Key is: " + o);
alert("Value is: " + val);
for(var b in val)
{
alert("Inner Key is: " + b);
alert("Inner Value is: " + val[b]);
}
}
Maby this will help you:
for (var item in result[0]) {
var key=item;
var val=b[item];
alert('b['+key+']='+val);
}
Good luck!
Maybe as a clarification for the other answers:
result[0].name
is the same as
result[0]["name"]
However,
result[0][name]
would use whatever the current value of name is. E.g.
var name = "surname";
if (result[0][name] == result[0].surname) // this is true
Related
I have an ajax call that returns a Serialized JSON string with various keys and values within it, I want to loop through these values and assign each individual key and value to a different label, I already have 8 labels set up. (I am quite new to Javascript so any help or constructive feedback would be greatly appreciated)
Haven't tried much as I am quite new to JavaScript
var obj = response.ret.SearchCriteria;
var resultJSON = obj;
var result = $.parseJSON(resultJSON);
var count = Object.keys(result).length;
for (i = 1; i < count; i++) {
var c = $('#lbl' + [i]);
$.each(result, function(k, v) {
c.text(k + ' is ' + v);
});
};
I have 6 labels and the last item of the JSON array (String) is displayed in each label
I believe your issue is why only last item of JSON array is being displayed in each label.
This is because of c.text(k + ' is ' + v).
Here the existing text content is replaced with every iteration of 'each' loop
Instead, you can consider doing this, which will append existing content as well with $.each loop.
c.text(c.text() + k + ' is ' + v)
OR
Simply
c.append( k + ' is ' + v)
If I am wrong in my assumption, please describe your scenario more, so that we can help you out :)
I am trying to perform a simple addition on data I have gathered from an external source via JSON. The data I am getting is being returned as a string but is a number so I have tried using both parseInt() and Number() to no avail. I have shown a simple section of the code below:
var total_energy = 0;
var energy_val;
$.each(result.report.food.nutrients, function (i, v) {
if (v.name == "Energy"){
energy_val = v.value;
var energy = Number(energy_val);
total_energy = total_energy + energy;
console.log("energy " + energy);
console.log("totalenergy " + total_energy);
energy_val = "";
energy = 0;
}
}
The console returns the correct value for energy each time but the totalenergy value just seems to stay the same as the energy value. The sum doesn't seem to have any affect. Could anyone tell me where I am going wrong with this problem?
change console.log("energy " + total_energy); to console.log("energy " + energy);
try parseInt your values... can be this
I doubt if its due to the closure created in the loop where you are iterating over the items. Try the following code.
var total_energy = 0;
var energy_val;
$.each(result.report.food.nutrients, function (i, v) {
var item = v;
//Calling calculateEnergy() function so that each 'item' is the current instance 'v' value.
(function calculateEnergy(itemClicked))(item);
}
function calculateEnergy(itemClicked){
if(itemClicked.name == "Energy"){
energy_val = itemClicked.value;
var energy = Number(energy_val);
total_energy = total_energy + energy;
console.log("energy " + energy);
console.log("totalenergy " + total_energy);
energy_val = "";
energy = 0;
}
}
I have put comments within the code.
Update console.log() is buggy with ajax requests. So instead of logging, try creating an html div and populate the values there.
I've got an array like this
pages['name'] = "Home";
pages['childs'][0]['name'] = "Sub page 1";
pages['childs'][1]['name'] = "Sub page 2";
pages['childs'][2]['name'] = "Sub page 3";
pages['childs'][2]['childs'][0]['name'] = "Sub sub page 1";
My problem is that I need to change portions of the array for example.
pages['childs'][0] = otherarray;
// or
pages['childs'][2]['childs'][0] = otherarray;
Obviously if otherarray was a string I can easily do something like
eval('pages' + where + ' = "' + stringvalue + '"');
But I've an array as value so I can't do
eval('pages' + where + ' = "' + otherarray + '"');
because the code executed will be
pages['childs'][0] = [object object];
What's the solution? Thanks
Rather than screw around with eval and stringifying things, you should just build an accessor. Many would agree that using eval like this is just bad practice in every way. I don't know if combining it with stringify makes it worse, but it certainly feels dirty.
Here's a basic, fairly stupid accessor, but it should give you the idea.
// Arguments: array to modify; new value; series of nested array keys.
function modifyArray(base, value){
var refObj = base;
for (var ii=2, max=arguments.length; ii < max; ii++){
if (!refObj) {
return false; // we supplied an invalid key.
}
if (ii == max-1){
refObj[arguments[ii]] = value;
return true;
}
refObj = refObj[arguments[ii]];
}
return false; // probably forgot to include keys.
}
modifyArray(pages, otherarray, 'childs', 2, 'childs', 0);
http://jsfiddle.net/2ts78brg/
For me this solution works
eval("pages" + where + " = JSON.parse('" + JSON.stringify(otherarray) + "')");
It sounds more like a workaround then a solution but it works and for me it's enough.
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;
}
I'm looking to loop through a JSON array and display the key and value.
It should be a simplified version of the following post, but I don't seem to have the syntax correct: jQuery 'each' loop with JSON array
I also saw the post Get name of key in key/value pair in JSON using jQuery?, but it also seemed like lots of code for a simple activity.
This illustrates what I'm looking for (but it doesn't work):
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
There is no mandatory jQuery requirement, but it is available. I can also restructure the JSON if it cuts down the required code.
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
Live demo.
var obj = $.parseJSON(result);
for (var prop in obj) {
alert(prop + " is " + obj[prop]);
}
You can get the values directly in case of one array like this:
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName']; // return ''Doe'
result['Email']; // return 'johndoe#johndoe.com'
result['Phone']; // return '123'
The following should work for a JSON returned string. It will also work for an associative array of data.
for (var key in data)
alert(key + ' is ' + data[key]);
Parse the JSON string and you can loop through the keys.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var data = JSON.parse(resultJSON);
for (var key in data)
{
//console.log(key + ' : ' + data[key]);
alert(key + ' --> ' + data[key]);
}
The best and perfect solution for this issue:
I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!
Click here to see the full solution
var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
eval("var toObject = "+ rs + ";");
alert(toObject.message);