bastifix
bastifix

Reputation: 483

Javascript: adding data dynamically to array

I've an array with players in it. Every player has its name (array[i].name) and power (array[i].power). Now I want to add dynamically grades for every player. Every grade should have its own categories with achieved points.

Data structure example:

array[i].football.shooting=5;

array[i].football.dribbling=3;

I tried to push the name of the grade first to each player and then add the categories as an extra array. But not even .push() worked as I mentioned:

for (var i = 0; i < array.length; i++) {
        array[i].push(gradeName);
}

Can please someone give me a hint how to solve this?

Thank you very much!

Upvotes: 1

Views: 925

Answers (4)

noa-dev
noa-dev

Reputation: 3641

In JavaScript I'd suggest working with objects within array - I know thats what you are already doing but look at a architecture like that:

var players = [
   {
      name: "Playername1",
      attributes: [
         {name: "football", skill_level: { dribbling: 1, passes: 3}},
         {name: "basketball", skill_level: {range_shot: 3, passes:1}}
      ]
   }
]

With that architecture you can push an entire new player object to the array. You can also loop through the attributes, check for existing attributes, add missing ones and edit current ones -> great variety.

if you'd like to add an attribute to that architecture it would be like:

var newSkill = { name: "flying plane", skill_level: { flight: 4, landing:0 }};

for(var i = 0; i < players.length; i++){
     players[i].attributes.push(newSkill);
}

Hope this could help a bit.

UPDATE

Let's say you have received a user input through a form and save that to a variable userInputName

Then you can simlpy add a dynamically named attribute like that :

var newSkill = { name: userInputName, skill_level: { flight: 4, landing:0 }};

for(var i = 0; i < players.length; i++){
     players[i].attributes.push(newSkill);
}

Upvotes: 1

michelem
michelem

Reputation: 14590

Probably something like this:

JSFiddle

var array = [{
    name: 'hello',
    power: 1
}, {
    name: 'world',
    power: 3
}];

var getGrades = function () {
    return {
        shooting: 5,
        dribling: 3
    };
}

for (var i = 0; i < array.length; i++) {
    array[i].football = [];
    array[i].football.push(getGrades());
}

console.log(array);

You should post also your desired output to get a specific answer.

Upvotes: 1

Gene R
Gene R

Reputation: 3744

According to your data structure example adding should be something like this:

var grade = 'footbal';
var category = 'shooting';
var points = 5;
array[i][grade] = array[i][grade] || {};
array[i][grade][category] = points;

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68383

This is an associative array not your regular array

try

for (var i = 0; i < array.length; i++) {
        array[i][ gradeName ] = {};
}

Upvotes: 0

Related Questions