Naming objects inside of an array dynamically - javascript

I'm quite new to JavaScript and programming in general and figured I'd hone my abilities by working on a small project. The idea is that I have a form for information on an event, an input for the name, date, time and a small thumbnail image.
I want each event to be an object inside of an array, so I would have something like:
var concerts = {};
for (var i = 1; i < 11; i++) {
window["concert"+i] = new Object();
}
and the array would end up being something:
var concerts = [concert1, concert2, concert3]
and so on.
How could I get this loop to work so that it would take the 3 parameters and create a new object in the array named 'concert'+i? Thanks for reading!

Concerts must be an array:
var concerts = [];
for (var i = 0; i < 10; i++) {
concerts[i] = {
//maybe also giveit a name if you want to:
name:"concert"+i
};
}
You can access it like this:
concerts[0].name="Wacken";//first concert...
Note that this:
window["concert"+i] = new Object();
is very bad style...

First you declare a variable concerts of type object. But you want an array. That first line makes your code very confusing.
You have to start with an empty array:
var concerts = []; // alternatively: new Array();
In the end you'd like to have a structure like this:
[
{ /* object 1 */ },
{ /* object 2 */ }
]
Now you can run a foor-loop and populate the array:
for (var i = 0; i <= 10; i++) {
concerts.push({['concert' + i]: {}});
}
This will return something like:
[
{'concert0': {}},
{'concert1': {}},
// skipped
{'concert10': {}}
]
Later you can populate the objects. This is however not a very nice style. Maybe you should reconsider if it is really necessary to give a name to every object like concert0...10.
Go rather for:
var concerts = [
{
'name': 'concert0',
'location': 'somewhere'
}
// continue with other objects
];

Related

how can I filter an array without losing the index?

I have two really long arrays containing "picture names" and "picture files". The first one represents the actual name of the pictures, while the second one is just the file name. For example:
picturenames[0] = '0 - zero';
picturenames[1] = '1 - one';
picturenames[2] = '1 o\'clock';
...
picturefiles[0] = 'numbers-zero.jpg';
picturefiles[1] = 'numbers-one.jpg';
picturefiles[2] = 'time-1.jpg';
...
I have about 1000 items in each array in several languages (the picture files are always the same). I'm "recycling" these arrays from the previous application to save some time and avoid rewriting everything anew.
Desirable functionality: using the user's input in a textbox I want to filter the picturenames array and then show the correspondant picturefiles image.
The issue I'm facing: when I filter the picturenames array I lose the index and I can't "reach" the picture file name.
This is the code I'm using to filter the picturenames array.
var matches = picturenames.filter(function(windowValue){
if(windowValue) {
return windowValue.indexOf(textToFindLower) >= 0;
}
});
What would be the best way to do this?
UPDATE: the solution proposed by Ahmed is the best one, but for time reasons and negligible performance issues I'm just using a for loop to search trough the array, as follows:
var matchesCounter = new Array();
for (i = 0; i < picturenames.length; i++) {
if (picturenames[i].indexOf(textToFindLower) >= 0) {
matchesCounter.push(i);
}
}
console.log(matchesCounter);
for (i = 0; i < matchesCounter.length; i++) {
console.log(picturenames[i]);
console.log(picturefiles[i]);
}
Try this:
const foundIndicies = Object.keys(picturenames).filter(pictureName => {
pictureName.includes(textToFindLower)
});
// reference picturefiles[foundIndicies[0]] to get the file name
Though, it would be far nicer to have both the name and the file in a single object, like so:
const pictures = [
{
name: '0 - zero',
file: 'numbers-zero.jpg',
},
{
name: '1 - one',
file: 'numbers-one.jpg',
}
];
const foundPictures = pictures.filter(picture => picture.name.includes('zero'));
if (foundPictures[0]) console.log(foundPictures[0].file);
You can add one property index during the filtering time, then later on you can use the index.
var matches = picturenames.filter(function(windowValue, index){
if(windowValue) {
windowValue.index = index;
return windowValue.comparator(textToFindLower) >= 0;// Need to define comparator function
}
});
Later on you can access by using like follows:
picturefiles[matches[0].index]
However, the solution will work on object, not primitive type string.
If your data type is string, then you have to convert as object and put the string as a property value like name. The snippet is given below:
var picturenames = [];
var picturefiles = [];
picturenames.push({name:'0 - zero'});
picturenames.push({name:'1 - one'});
picturenames.push({name:'1 o\'clock'});
picturefiles.push({name:'numbers-zero.jpg'});
picturefiles.push({name:'numbers-one.jpg'});
picturefiles.push({name: 'time-1.jpg'});
var textToFindLower = "0";
var matches = picturenames.filter(function(windowValue, index){
if(windowValue) {
windowValue.index = index;
return windowValue.name.indexOf(textToFindLower) >= 0;
}
});
console.log(matches);

javascript: array with unknown length and unknown index names

I am making a program of a football league.
A example of a league:
team1
team2
team3
I want to save (increase) number of players for each team like
var teamArray = [];
teamArray[team1] = 1;
teamArray[team2] = 2;
and I am doing in the body of some functions like:
function 1(){}
function 2(){}
function .(){}
function .(){}
function .(){}
function n(){}
but this works only when i "teach" javscript that the array is an integer array... with somethin like
teamArray[team1] = 0;
teamArray[team1] = teamArray[team1] + 1;
but the problem is every time when i come to one of my functions, i have to set my array element to 0 and that makes the whole calculation wrong...
Could anyone give me a hint please?
My Idea was to was to set each array element to 0 from the beginning, but i dont know at the beginning of my game how many teams i will have today, that why i implemented the array like:
var teamArray = [];
Use a JavaScript object instead. Something like:
var teamObject = {
team1: 3,
team2: 5,
team3: 7,
};
Or, perhaps an array of objects:
var teamArray = [
{ name: 'team1', players: 3 },
{ name: 'team2', players: 5 },
{ name: 'team3', players: 7 }
];
The object is easier to access if all you want is to get or set the number of players:
teamObject.team1 += 1;
but an array is easier to loop through and can be ordered:
for (var i=0,j=teamArray.length; i<j; i++) {
console.log(teamArray[i].name + " has " + teamArray[i].players + " players");
}
You can increment the number of team members by testing the current number first, and if it does not exist, you initialise it with 0 on the fly. All that can be done in one expression with a logical OR (||):
teamArray[team1] = (teamArray[team1] || 0) + 1;
This will not destroy the previous value you had and work like a simple + 1 in that case.
You should define your teamArray as object, although it will work with array as well (since that is an object as well):
teamArray = {}
The name is then of course a bit confusing, but I'll stick with it.
Whenever you need to iterate over the teams you have collected, then you can use a for loop like this:
for (var team in teamArray) {
console.log(team, teamArray[team]);
}
thanks for all your help!
I did it like this now:
var listItems = $("#teamsDropdown li");
listItems.each(function(idx, li) {
var team = $(li).text();
TeamPlayerQuantities[team] = 0;
});
and increasing the qnty of players wiht functions like:
function1(team){
TeamPlayerQuantities[team] ++;
}

Same JSON ojbects in array when receiving differnt array elements

In my NodeJS app i get an JSON object within jade (which works fine). Here in i tried to collect(srcTweets) only the relevant data and return this in a new JSON object(stgTweets). Which i use for Dynamic Table use.
Here fore i use the following scrip:
var srcTweets = [];
var srcTweets = !{JSON.stringify(tweets)};
var aantalSrcTweets = srcTweets.length;
//Loop throug all tweets and collect all relevant elementen from srcTweet:
var stgTweet = {}
var stgTweets = [];
console.info('----------START LOOP--------------------');
for(var i = 0; i < aantalSrcTweets; i++){
console.info(i);
stgTweet.Id = srcTweets[i]._id;
stgTweet.userId = srcTweets[i].user.id;
stgTweet.userFollowerCount = srcTweets[i].user.followers_count;
stgTweet.userFriendCount = srcTweets[i].user.friends_count;
stgTweet.userFavouritesCount = srcTweets[i].user.favourites_count;
stgTweet.text = srcTweets[i].text;
stgTweet.coordinates = srcTweets[i].coordinates;
stgTweet.userLocation = srcTweets[i].user.location;
stgTweets[i] = stgTweet;
console.info(stgTweets[i]);
console.info(i);
}
console.info('----------END LOOP--------------------');
//here i get the same items
console.info(stgTweets[0]);
console.info(stgTweets[1]);
When i print different index numbers of the array "stgTweet[0] and stgTweet[1]" the same data is showed. I tried to figure it out by logging the elements in the for loop , but that looks fine. And i realy don't know where to look futher.
How do i fill the array with different objects in stead of the same object, what happens in the script above.
Here is an example of the srcTweets:
[
Object {
_id="56e19eb1ac5e621e0797c423",
truncated=false,
text="#Model_Symphony nu ja,
s... prima Energiequelle...",
more...
},
Object {
_id="56e1a73eac5e621e0797c424",
truncated=false,
text="Vandaag aangekondigd doo...",
more...
},
Object {
_id="56e1a7b4ac5e621e0797c425",
truncated=false,
text="Mooi bedrijfsbezoek aan ...",
more...
}
]
The reason is because you're reusing the same object for every element in the array and objects are assigned by reference in Javascript, so stgTweets[0] === stgTweets[1].
What you could do instead is move your stgTweet declaration inside the loop (or just re-assign the value directly as shown below) so that a new object is created for each array element:
var stgTweets = new Array(aantalSrcTweets);
for (var i = 0; i < aantalSrcTweets; i++){
stgTweets[i] = {
Id: srcTweets[i]._id,
userId: srcTweets[i].user.id,
userFollowerCount: srcTweets[i].user.followers_count,
userFriendCount: srcTweets[i].user.friends_count,
userFavouritesCount: srcTweets[i].user.favourites_count,
text: srcTweets[i].text,
coordinates: srcTweets[i].coordinates,
userLocation: srcTweets[i].user.location
};
}

How to create multiple objects based on dynamic data?

Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}

Insert complex value to an existing array in JavaScript

I need to create a list of struct type (complex model) on JavaScript using ASDP.NET MVC3
var myItems = new Array(#Model.Count());
var CreatedItem;
for (i = 1 ; i<= #Model.Count()-1;i++)
{
CreatedItem = {
'DayPartID': i,
'Name': $("#Name_"+i).val(),
'IsEnable': $("#IsEnable_"+i).val(),
'Time': $('#timepicker-'+ i).val()
};
myItems.push(CreatedItem);
alert(myItems[i]);
}
Problem is that I can not obtain "myItems" filled correctly after repetitive structure "for" ends.
You're initializing your array like:
var arr = new Array(2);
Then you do:
arr.push("foo");
This will give you:
[ undefined, undefined, "foo" ]
Either change the initialaztion to an empty array like:
var myItems = [];
Or don't push, but set, like:
myItems[i] = CreatedItem;
Also, your loop starts at 1 - that's weird. Change to:
for (i = 0 ; i < #Model.Count(); i += 1) {

Categories

Resources