How to loop throught objects with arrays as properties - javascript

This is my code:
I want to get the first value of the arrays in every property, but it doesnt work. Thanks for help.
var arena = {
o1: ['gate',1,1],
o2: ['block',1,1]
};
$(document).ready(function(){
var canvas = document.getElementById('canvas.arena');
var xpercent = canvas.width/100;
var ypercent = canvas.height/100;
for (var key in arena) {
if (arena.hasOwnProperty(key)) {
console.log(key + " -> " + arena[key[0]]);
}
}
});

Almost:
for (var key in arena) {
console.log(key + " -> " + arena[key][0]);
}
key will always be a property, no need to check.

you are very close:
var arena = {
o1: ['gate',1,1],
o2: ['block',1,1]
};
$(document).ready(function(){
for (var key in arena) {
console.log(key + " -> " + arena[key][0]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
prepared this fiddle:
https://jsfiddle.net/njvf58ow/1/

Related

Javascript object set to another object is undefined

For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}

Steam trade-offer-manager get items info shorten

I'm trying to build a new project.
It's going to be a tradebot for a website, now to store my received items into my database i whould like some info send with each item (being the name , asseid , tradeid,...).
The following code works.
offers.on('receivedOfferChanged', function (offer, oldState) {
logger.info(offer.partner.getSteam3RenderedID() + " Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));
// Alert us when we accept an offer
if (offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
offer.getReceivedItems(function (err, items) {
if (err) {
logger.error("Couldn't get received items: " + err);
} else {
var names = items.map(function(item) {
return item.name;
});
var assetids = items.map(function(item) {
return item.assetid;
});
// Log a comma-separated list of items received
logger.info("Received: " + names + " " + assetids.join(', '));
}
});
}
});`
But the thing is, is there any way to shorten the following code :
var names = items.map(function(item) {
return item.name;
});
var assetids = items.map(function(item) {
return item.assetid;
});
So it gets the item name , assetid, ... out of the array and stores them in sperate variables ?
You can use push() method to add values into both arrays in a single loop. Try:
var names = [],
assetids = [];
items.forEach(function(item) {
assetids.push(item.assetid);
names.push(item.name);
});

JavaScript foreach Key Value array

I have just this array :
var sArray = {856:"users", 857:"avatars", 858:"emails"};
and I want to use forEach in a way to get key and value from that:
key = 856
value = user
My $.each code doesn't return the result I'm expecting, and I get instead:
856:user
I must be separate that with : to get key and value from this array.
My code is:
$.each(template_array, function(key, value) {
console.log("key: " + "value: " + value);
});
How to access key and value without separate?
Just take Object.keys for the keys and Array.prototype.forEach for the values in plain Javascript.
var sArray = { 856: 'users', 857: 'avatars', 858: 'emails'};
Object.keys(sArray).forEach(function (key) {
document.write('key: ' + key + ', value: ' + sArray[key] + '<br>');
});
Just concatenate them using +
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
$.each(template_array, function(key, value) {
console.log('key:' + key + ', value:' + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
UPDATE :
I think you have an array then use the following code
var template_array = ['856: users',
'857: avatars',
'858: emails'
];
template_array.forEach(function(v) {
v = v.split(':');
console.log('key:' + v[0] + ', value:' + v[1]);
});
try this one
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
var date = [];
$.each(template_array,function (key , val){
date.push({key:key, value:val})
});
console.log(date)
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
for (key in template_array) {
console.log('key:' + key + ', value:' + template_array[key]);
});

Access object property in array of objects

I have this set
var data = [
{"outlet_name":"Easy Lane Supermart","20130102_20130108":"0"},
{"outlet_name":"Eunilaine Foodmart Kalayaan","20130102_20130108":"0"},
{"outlet_name":"PUREGOLD PRICE CLUB, INC - VISAYAS","20130102_20130108":"0"}
];
$.each(data, function (i, item) {
$.each(item, function (k,v) {
$('#result').append(k,v);
});
});
How can I make it only view all the values of outlet_name without using the item.outlet_name?
$.each(data, function (i, item) {
console.log(item.outlet_name);
});
Or without jQuery:
for (var i=0;i<data.length;i+=1) {
console.log(data[i].outlet_name);
}
Ok, if you want to iterate over each object you can write:
$.each(data, function (i, item) {
console.log("Values in object " + i + ":");
$.each(item, function(key, value) {
console.log(key + " = " + value);
});
});
This will provide exact answer...
var data = [
{"outlet_name":"Easy Lane Supermart","20130102_20130108":"0"},
{"outlet_name":"Eunilaine Foodmart Kalayaan","20130102_20130108":"0"},
{"outlet_name":"PUREGOLD PRICE CLUB, INC - VISAYAS","20130102_20130108":"0"}
];
for(i=0;i<data.length;i++){
for(var x in data[i]){
console.log(x + " => " + data[i][x]);
}
}
If anyone is needing to do this from a JSON string for example
var myJson = [{"Code":"slide_1.png","Description":"slide_1"},{"Code":"slide_2.png","Description":"slide_2"},{"Code":"slide_3.png","Description":"slide_3"}]
You can use
var newJsonArray = JSON.Parse(myJson) and you will get
Array[3]
0
:
Object
1
:
Object
2
:
Object
At which point you can access it by simply saying newJsonArray[i].Code or whatever property inside the array you want to use. Hope this helps!

How to attach click event at runtime when i have all ids in an array that gets populated when document is ready?

I have the following code,
<script type="text/javascript">
$(document).ready(function () {
var dataAnalysisDataFileTableIDs = $("#dataAnalysisDataFileTable tr[id]").map(function () { return this.id; }).get();
//for(var key in dataAnalysisDataFileTableIDs) {
// var id = "#" + dataAnalysisDataFileTableIDs[key];
// $(id).click(function () {
// alert("[" + index + "][" + value + "]");
// });
//}
//$.each(dataAnalysisDataFileTableIDs, function (index, value) {
// var id = "#" + dataAnalysisDataFileTableIDs[key];
// $(id).click(function () {
// alert("[" + index + "][" + value + "]");
// });
//});
$("#dataAnalysisDataFileTable tr[id]").each(function (i, elem) {
$(elem).click(function () { alert("[" + i + "][" + this.id + "]"); });
});
$("#aaa").click(function () {
alert("meow");
});
});
</script>
and it doesn't work i also tried the one in the comments section which does the same as "for in" it doen't work but when i attach click to the id #aaa it works fine how do i approach this problem when i have all the ids in the array and i want to be able to attach events to them?
How about just using each ? Like so:
<html>
<head><script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script></head>
<body>
<table id="dataAnalysisDataFileTable">
<tr id="foo"><td>foo</td></tr>
<tr id="bar"><td>bar</td></tr>
</table>
<script type="text/javascript">
$(document).ready(function () {
$("#dataAnalysisDataFileTable tr[id]").each(function(i, elem) {
$(elem).click(function() { alert("[" + i + "][" + this.id + "]") } );
});
});
</script>
</body>
</html>
I've patched the possible errors. I cannot resolve the value variable though.
for(var index=0, length=dataAnalysisFileTableIDs.length; index++) {
var key = dataAnalysisFileTableIDs[index];
var id = "#" + dataAnalysisFileTableIDs[key];
$(id).click(function () {
/* Value ? It's not defined*/
alert("[" + index + "][" + /*value +*/ "]");
});
}
dataAnalysisFileTableIDs is an array. To loop through an array, you have to use the for ( init_index ; condition ; increment ) loop. The key can be obtained through name_of_array[index].

Categories

Resources