Question

Within my node.js app I have managed to retrieve userinput and proceed to scrape a unique table for each user to recieve the following associative array, called self.items

When I call the following:

console.log(self.items)

I recieve the following output for a specific user.

[ { Wins: 5,
    Losses: 1,
    Points: 33 },
  { Wins: 3,
    Losses: 1,
    Points: 21 },
  { Wins: 3,
    Losses: 0,
    Points: 18 } ]

Because I intend to visualize the data with d3.js I would like to simplify the associative array into 3 managable simple arrays, such that for each key there would be a simple array created with all of the corresponding values. The following output is what I am seeking:

console.log(wins) => [5,3,3]

console.log(losses) => [1,1,0]

console.log(points) => [33,21,18]

How can I go about doing this?

Était-ce utile?

La solution

Create 3 empty arrays (wins, losses, points). Simply loop through your array using a for...loop which using the length to determine how many elements there are.

Use push() to add the individual parts to their respective arrays.

var data = [ 
{ 
    Wins: 5,
    Losses: 1,
    Points: 33 
},
{ 
    Wins: 3,
    Losses: 1,
    Points: 21 
},
{ 
    Wins: 3,
    Losses: 0,
    Points: 18 
}];

var wins = [], losses = [], points = [];
for(var i=0; i< data.length; i++)
{
    wins.push(data[i].Wins);
    losses.push(data[i].Losses);    
    points.push(data[i].Points);    
}

console.log(wins);
console.log(losses);
console.log(points);

Fiddle

Autres conseils

Because you know the structure, you can simply do it.

var wins = [], losses = [], points = [], item;
for (var i=0; i < self.items.length; i++) {
    item = self.items[i];
    wins.push(item.Wins);
    losses.push(item.Losses);
    points.push(item.Points);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top