jquery: adding custom key value to object - javascript

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

Related

Looping through each item from JSON to display plane information

Question
How can i set up a working example of of these planes.
Background
I have the first part working, so it seems that perhaps my loop is off? I can at least pull the number of planes. But having a problem displaying all the planes.
Here is my Demo on CodePen
I am looking at the documentation from https://developers.wargaming.net/reference/all/wowp/encyclopedia/planes/?application_id=demo&r_realm=eu
but they don't have a fully functioning example. I want to show the name of the plane, country, and show a large image. I can style it later but need a working example to help me understand and get started.
Code
API
I am pulling data from https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo
JSON output
HTML
<p>There are a total of <span id="planeQuantity"></span> planes in the database.</p>
<ul id="planes"></ul>
jQuery from
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
Javascript
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
var name = data.id.name_i8n;
var nation = data.id.nation;
var lrgImg = data.id.images.large;
$(data).each(function(){
console.log($(this).id);
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
})
I adjusted your code a bit. Some comments:
your data.data is a Object. so, you can use for (key in object) for each key iteration (you can use jQuery's each too, but this is a pure JS approach);
name_i8n is, actually, name_i18n;
put all your var = name, var = nation and var = lrgImg into inside the loop.
Final code:
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
for (key in data.data) {
var item = data.data[key];
var name = item.name_i18n;
var nation = item.nation;
var lrgImg = item.images.large;
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
}
})
Working pen: http://codepen.io/mrlew/pen/vgaexb
Edited with some explanation
You received a data Object that have a data key whose value is a huge Object with this structure (more or less):
{
"7290": { /* ... */ },
"7291": {
"name_i18n": "North American FJ-1 Fury",
"nation":"usa",
"images":{
"large":"http://worldofwarplanes....png",
/* ... */
},
/* ... */
},
"7292": { /* ... */ }
}
So, to iterate over all keys of data.data keys we can use for (key in data.data) { }.
In each iteration, key variable will be assigned to a object key: 7290, 7291, 7292. So, to access it's value, we use data.data[key] (will be data.data["7291"], for instance), and assigned the variable item with the value.
Using brackets like this is one way in JavaScript to retrieve a value from an Object. Another way is to use dot notation (but you can't use dot notation with a key that's a number).
This is valid:
data["data"]["7291"]
This is invalid:
data.data.7291
You should set the values of name, nation and lrgImg inside each. So the elements you append won't all have the same thing. And you should loop through the data object that is inside your data object (data.data). Like this:
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
$.each(data.data, function(key, value){
var name = value.name_i18n; // get the name of this data entry
var nation = value.nation; // get the nation of this data entry
var lrgImg = value.images.large; // ...
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
});
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/? application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
$.each(data.data, function(i, e) {
var name = e.name_i18n;
var nation = e.nation;
var lrgImg = e.images.large;
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
});
You need to iterate through data.data object. Since you aren't working with dom nodes use $.each() instead of $.fn.each()
$.each(data.data, function(key, obj){
console.log(key) // "4101"
console.log(obj.name) // "type=91"
})

How to read object string using jquery?

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);
});

Loop and get key/value pair for JSON array using jQuery

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);

How to make jQuery objects from an array?

anArray = ['thing1','thing2','thing3'];
$.each(anArray, function (i,el) {
var object = 'name.space.' + el;
var selector = 'node-' + el;
var object = $('#' + selector);//need object here to be interpreted as it's value
//as if: var name.space.thing1 = $('#' + selector);
});
such that these are usable jQuery objects:
console.log(name.space.thing1);
console.log(name.space.thing2);
console.log(name.space.thing3);
I feel like eval() is involved. I'm hydrating navigation selectors so as pages are added/removed, we just update the array. We could build the array from the nav nodes, but either way, we still need to be able to make these namespaced selectors...
You will have to use bracket notation:
var array = ['thing1', 'thing2'];
var object = {};
object.space = {};
$.each(array, function () {
object.space[this] = $('#node-' + this);
});
console.log(object.space.thing1); // [<div id="node-1">];
I am not sure what are you trying to accomplish, but
name.space[el] = $('#' + selector);
might work.
Object properties are always accessible with the bracket notation as well. This means that obj.xy is just the same as obj['xy'], but the latter is more flexible and can be used in situations like yours.
var anArray = ['thing1','thing2','thing3'];
var name = {space:new Array()};
$.each(anArray, function (i,el) {
var selector = 'node-' + el;
name.space[el] = $('#' + selector);
});

How can I display object content without specifying the attributes?

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

Categories

Resources