ntgCleaner ntgCleaner - 26 days ago 12
jQuery Question

Create a single object from multiple foreach loops

I am trying to create an object for a single player that has all of that players ranks over all of the seasons available.

I've been getting the information and am iterating through it. The each loops work, but I think I'm overwriting parts of the object as I iterate through. I'm not sure how to get all of the information without overwriting part of the object.

Here's what I have so far:

var playerObj;
var username = page.find('.profile_player-name').text();
if(username) {
var seasons = page.find('.profile_seasons .tab-pane');
var seasonsObj;
$.each(seasons, function(i) {
var statsObj;
var season = $(seasons[i]);
var season_number = season.attr('id');
var season_playlists = season.find('.row > .col-md-3');
$.each(season_playlists, function(i) {
var playlist = $(season_playlists[i]);
var playlist_title = playlist.find('.panel-title').text();
var playlist_rating = playlist.find('.profile_tier-name').text().match(/\d+/g);
if(playlist_rating) {
playlist_rating = playlist_rating[0];
}
var playlist_rank = playlist.find('.profile_tier-name strong').text();
var playlist_rank_icon = "http://rocketleaguestats.com/" + playlist.find('img').attr('src');
statsObj = {
title:playlist_title,
rating:playlist_rating,
rank: {rank_name:playlist_rank, rank_icon:playlist_rank_icon}
};
console.log(statsObj);
});
});
} else {
return false;
}


This should return something like this:

object = {
username: "name",
seasons:
season_1:
rank:
rank_name: "Gold",
rank_icon: http://....jpg,
rating: "800",
title: "Ranked Standard"
season_2:
rank:
rank_name: "Gold",
rank_icon: http://....jpg,
rating: "800",
title: "Ranked Standard"
season_3:
rank:
rank_name: "Gold",
rank_icon: http://....jpg,
rating: "800",
title: "Ranked Standard"
}


But I'm not sure how to add each different season as it's own piece of the object, with the different variable name (season_1 vs season_3).

How do I add each
season_#
as it's own part of the object dynamically? There may be 1 to many seasons.

Answer

If you need to add properties to an object, but the property name is variable, you can use the [] syntax. In your case, you can achieve what you want with a few simple changes.

First, just initialize your object

var seasonsObj = {
    username: username,
    seasons: {}
};

Then, in your loop, you can add properties to seasonsObj.seasons like this:

seasonObj.seasons['season_' + i] = statsObj;
Comments