I am pretty new to javascript and jquery. I currently have a xml file that I'm trying to parse by using jquery and javascript, but for some reason the values that I store on the array are not being saved.
var categories = new Array(); // Array for the categories
var data = {
categories: []
};
var sources = [
{
src:'',
title: '',
desc: ''
}];
var i = 0;
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
sources[i] = [];
sources[i].src = el.find('media\\:content, content').attr('url');
sources[i].title = el.find("title").text();
sources[i].desc = 'Moscone Center';
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
}
i++;
});
});
If i do console.log(categories) it prints all the categories on the array but if I do console.log(categories.length) I keep getting 0...
console.log(categories.length); // This should be outputting 5 but I keep getting 0 for the size.
for (var i=0; i<categories.length; i++) {
var category = {
name: categories[i],
videos: []
};
}
I appreciate any help that anybody can give me. Thanks
$.get function is asynchronous so you should try putting the logging inside the callback function.
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
....
});
console.log(categories.length);
});
Related
I its basic but I am new to javascript. I am trying to loop through the array and match the objects that == my key.
this is what i am using right now, it works but i am only matching the first object that matches, sometimes there will be multiple objects that match.
Here is what i have now
var chartSeries = chartService.getSeries();
var marker.options.subdivision.id = 1345
var matchingSeries = Enumerable.From(chartSeries).Where('x => x.id == "' + marker.options.subdivision.id + '"').ToArray();
var series = {
id: matchingSeries[0].id,
name: matchingSeries[0].name,
data: matchingSeries[0].data,
lineWidth: 5
};
I need to include a for loop to match all objects.
var subIdSeries = [];
var subId = marker.options.subdivision.id;
var series = {
id: matchingSeries[0].id,
name: matchingSeries[0].name,
data: matchingSeries[0].data,
lineWidth: 5
};
for (var i = 0; i < chartSeries.length; i++) {
if (subId == chartSeries.id) {
push.subIdSeries(subId)
}
}
Change
if (subId == chartSeries.id) {
push.subIdSeries(subId)
}
to
if (subId == chartSeries[i].id) {
subIdSeries.push(subId)
}
Without seeing the whole script, from what you have so far, I can suggest:
if (subId == chartSeries[i].id) {
subIdSeries.push(subId)
}
I am working for some common method in javascript, for that i have to call array dynamically.
var ddlText, ddlValue, ddl, lblMesg, ddlTextCacheList_Designation, ddlValueCacheList_Designation, ddlTextCacheList_Scale, ddlValueCacheList_Scale;
function cacheDes() {
var listDes = document.getElementById("<%=List_Designation.ClientID %>");
ddlTextCacheList_Designation = new Array();
ddlValueCacheList_Designation = new Array();
for (var i = 0; i < listDes.options.length; i++) {
ddlTextCacheList_Designation[ddlTextCacheList_Designation.length] = listDes.options[i].text;
ddlValueCacheList_Designation[ddlValueCacheList_Designation.length] = listDes.options[i].value;
}
}
function cacheScale() {
var listScale = document.getElementById("<%=List_Scale.ClientID %>");
ddlTextCacheList_Scale = new Array();
ddlValueCacheList_Scale = new Array();
for (var i = 0; i < listScale.options.length; i++) {
ddlTextCacheList_Scale[ddlTextCacheList_Scale.length] = listScale.options[i].text;
ddlValueCacheList_Scale[ddlValueCacheList_Scale.length] = listScale.options[i].value;
}
}
window.onload = function () {
cacheDes();
cacheScale();
};
I want to call array ddlTextCacheList_Scale or ddlTextCacheList_Designation for same method as we know 'ddlTextCacheList_' is common only we need to put 'Scale' or 'Designation' dynamicaaly by passing parameter.
Add:
I get some errors:
I suggest you to improve your cache to store all in one object to easy access...
For example:
var CacheStorage = {};
function cache(key, list) {
CacheStorage[key] = list.map(function(option){
return {text: option.text, value: option.value};
});
}
function del(key, index) {
CacheStorage[key].splice(index, 1);
}
cache('Scale', getElementByID('...').options);
cache('Designation', getElementByID('...').options);
del('Designation', 0);
I have two arrays of strings: hrefs, thumbs. Need to combine this arrays into another array with structure like below. How to do that ? For clarity - i need to use Lightview API to call function Lightview.show(elements), where elements is result array i need to build.
HTML:
one
two
three
Arrays:
var hrefs = $('.lv').map(function() { return $(this).attr('href'); }).get();
var thumbs = $('.lv').map(function() { return $(this).attr('thumbnail'); }).get();
The desired result array (elements):
{
{hrefs[0],
{
thumbnail: thumbs[0]
}
},
{hrefs[1],
{
thumbnail: thumbs[1]
}
},
...
}
I've started with this, but i think it is something wrong...
var e = new Array();
$.each(hrefs, function(i, value) {
e[i] = new Array();
e[i][0] = value;
e[i][1] = {thumbnail: thumbs[i]};
});
Do you mean this?
var result = $('.lv').map(function() {
var o = {};
o[$(this).attr('href')] = { thumbnail: $(this).attr('thumbnail') } };
return o;
}).get();
Are you looking for something like this?
var hrefs = $('.lv').map(function() { return $(this).attr('href'); }).get();
var thumbs = $('.lv').map(function() { return $(this).attr('thumbnail'); }).get();
var arr = {};
for (i in hrefs) {
arr[hrefs[i]] = {
thumbnail: thumbs[i]
}
}
Another suggestion, with minimal use of JQuery for faster execution
var lvs = $('.lv');
var arr = {};
for (i=0; i< lvs.length; i++) {
arr[lvs[i].getAttribute('href')] = {
thumbnail: lvs[i].getAttribute('thumbnail')
}
}
You're almost there. Just do:
var e = [];
$.each(hrefs, function(i, value) {
e[i] = [];
e[i] = [ value, {thumbnail: thumbs[i]} ];
});
Or even shorter:
var e = [];
$.each(hrefs, function(i, value) {
e[i] = [ value, {thumbnail: thumbs[i]} ];
});
Try this
var result = {};
$.each( hrefs, function ( index ) {
result[ hrefs[ index ] ] = { thumbnail: thumbs[ index ] };
});
There's a lot of code here, but the question has to do with the for loop at the bottom.
var dbo = openDatabase('xxx','1.0','myDatabase', 1048576);
var DropTableDeferred = new $.Deferred();
var CreateTableDeferred = new $.Deferred();
var InsertDeferred = new $.Deferred();
var SelectDeferred = new $.Deferred();
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'drop table myTable;'
,[]
,DropTableDeferred.resolve()
);
});
DropTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'CREATE TABLE IF NOT EXISTS myTable'
+ '(xxxID Integer NOT NULL PRIMARY KEY'
+ ',xxxName Varchar(128)'
+ ');'
,[]
,CreateTableDeferred.resolve()
);
});
});
CreateTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql("INSERT INTO myTable(xxxID,xxxName) VALUES(1,'A')");
myTrans.executeSql("INSERT INTO myTable(xxxID,xxxName) VALUES(2,'B')");
myTrans.executeSql(
"INSERT INTO myTable(xxxID,xxxName) VALUES(3,'C')",
[],
InsertDeferred.resolve()
);
});
});
InsertDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'SELECT * FROM myTable',
[],
function(tx, result) {
SelectDeferred.resolve(result);
}
);
});
});
SelectDeferred.done(function(result) {
var X = $('#result-template').html();
var template = Handlebars.compile(X);
var data = [];
for(var i=0;i < result.rows.length; i++) {
data.push(result.rows.item(i));
}
$('ul').append(template(data));
});
Q: Do I need to build a data array in order to call template(data), or can I pass the result variable directly?
And by 'result variable', what I mean is: result.rows, or result.rows.item, or some other combination.
Yes the value has passed directly in my html&javascript only project. In the code below, I get the results of the Sql and filling a dropdown box's options.
function fillLectureFromDB(tx) {
tx.executeSql('SELECT * FROM LECTURE', [], successFill, errorFill);
}
function successFill(tx, results) {
var len = results.rows.length;
for (var i=0; i<len; i++){
var elOptNew = document.createElement('option');
elOptNew.text = results.rows.item(i).code;
elOptNew.value = results.rows.item(i).code;
var elSel = document.getElementById('slExCode');
elSel.add(elOptNew, null);
}
}
IMHO you can, but to tell you the truth, it would've taken less time for you to try it out then to post the question. Just try:
$('ul').append(template(result.rows));
may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);