I've fetched data from PokeAPI, and now I'm struggling with creating an object containing this data. Data looks like this:
valueObject = {
"stats": [{
"base_stat": 45,
"effort": 0,
"stat": {
"name": "speed",
"url": "https://pokeapi.co/api/v2/stat/6/"
}
},
{
"base_stat": 65,
"effort": 0,
"stat": {
"name": "special-defense",
"url": "https://pokeapi.co/api/v2/stat/5/"
}
},
]
}
I wanted to create a function, that returns object with max value of base stat from all API calls (there is an array of data for each Pokemon). Object should look like this:
obj = {
speed: maxvalue of base.stat,
special - defense: max of base.stat,
...
}
Firstly I made separate assignment to every stat:
valueObject["speed"] = Math.max(...data.map(item => item.stats[0].base_stat));
// data is an array of all fetches
But I feel it can be done in one line, or one for loop. Unfortunately, I can't do that and I'm getting errors all the time. I tried mapping and using for loop:
// Option 1//
for (let i of data[0].stats) {
valueObject[data[0].stats[i].stat.name] = Math.max(
...data.map(item => item.stats[i].base_stat)
);
}
//Option 2 (it seems a bit off)//
valueObject[data[0].stats.map(item => item.stat.name)] = Math.max(
...data.map(item => item.stats.map(i => i.base_stat))
);
//I'm using data[0] to just get property names from any pokemon
So, can you help me figure it out?
EDIT: @mplungjan Ok I edited my post, but it doesn't seem to run anyway and I don't know why.
const maxStatsValues = data => {
//data array is passed as argument, but its elements look like this:
data[0] = {
"stats": [{
"base_stat": 45,
"effort": 0,
"stat": {
"name": "speed",
"url": "https://pokeapi.co/api/v2/stat/6/"
}
},
{
"base_stat": 65,
"effort": 0,
"stat": {
"name": "special-defense",
"url": "https://pokeapi.co/api/v2/stat/5/"
}
},
]
}
data[1] = {
"stats": [{
"base_stat": 72,
"effort": 0,
"stat": {
"name": "speed",
"url": "https://pokeapi.co/api/v2/stat/6/"
}
},
{
"base_stat": 90,
"effort": 0,
"stat": {
"name": "special-defense",
"url": "https://pokeapi.co/api/v2/stat/5/"
}
},
]
}
let obj = {};
data[0].stats.forEach(x => {
obj[x.stat.name] = Math.max(obj[x.stat.name] | 0, x.base_stat)
})
console.log(obj);
//my code:
// let valueObject = {};
// for (let i of data[0].stats) {
// valueObject[data[0].stats[i].stat.name] = Math.max(
// ...data.map(item => item.stats[i].base_stat)
// );
// }
// return valueObject;
return (obj);
};
array.reduceis probably the most suitable method.