Home > Blockchain >  Replacing multiple variables inside an Array & then list Javascript
Replacing multiple variables inside an Array & then list Javascript

Time:11-26

In the code below, I call an NBA api, and create an array from a specific bracket within it. However, this only gives me an array full of numbers, which are the NBA team's ID's. I'm trying to change all of the values into the Team name's themselves and list them. For example, '29' would be the Portland Trailblazers; 25 would be the Oklahoma City Thunder.

I've tried multiple threads with similar problems, but have yet to find something that works.

Code:

var idarray = [];

var idz = response.api.standings
for (var i = 0; i < idz.length; i  ) {

    idarray.push(idz[i].teamId);
}
console.log(idarray)

Array that prints out from above code:

 [
  '41', '5',  '20', '1',  '26',
  '24', '4',  '27', '38', '2',
  '6',  '21', '7',  '15', '10',
  '19', '14', '8',  '31', '23',
  '11', '30', '28', '16', '17',
  '40', '22', '9',  '29', '25'
]

CodePudding user response:

1. First of all, you need to map all team ID's to their names, something like this:

// key -> ID, value -> name
const teamNames = {
  25: 'Oklahoma City Thunder',
  29: 'Portland Trailblazers',
  ...
}

2. Then you can transform your array:

// For example idarray = [25, 29] initially
idarray = idarray.map(id => teamNames[id]);
console.log(idarray);

Output:

[ 'Oklahoma City Thunder', 'Portland Trailblazers' ]

Extra: mapped array is ready to print as standings list, for example:

for (let index in idarray) {
  console.log(`${index   1}. ${idarray[index]}`);
}

Output:

1. Oklahoma City Thunder
2. Portland Trailblazers
  • Related