I'm writing a NODE.JS code that presents the user with some data about his account inside a game.
It sends a GET request to the game API, and the API returns an array with the amount of "points" the player has with every "champion" in the game. The problem is, it doesn't return the "champion" names, only their IDs:
[
{
championId: 19,
championLevel: 7,
championPoints: 116531,
},
{
championId: 24,
championLevel: 6,
championPoints: 67710,
},
{
championId: 131,
championLevel: 6,
championPoints: 67233,
}
]
I have a list with all the IDs and their related champion names, as below. I want to know if there's a way to replace all the champion IDs with their according champion name, so I can print the array with the champion names instead of the IDs, to make it easier to understand the info. I only included 3 champions here to make it simpler, but the real array has 150 champions, so I need a way to "mass edit" it.
championId: 19 equals to champion name Warwick
championId: 24 equals to champion name Jax
championId: 131 equals to champion name Diana
What i would like to print is something like:
[
{
championName: Warwick,
championLevel: 7,
championPoints: 116531,
},
{
championName: Jax,
championLevel: 6,
championPoints: 67710,
},
{
championName: Diana,
championLevel: 6,
championPoints: 67233,
}
]
CodePudding user response:
The two useful array functions are map
and find
; map to transform the scores array, and find to do the important part of the transformation, which is looking up the name in the names array....
let scores = [{
championId: 19,
championLevel: 7,
championPoints: 116531,
},
{
championId: 24,
championLevel: 6,
championPoints: 67710,
},
{
championId: 131,
championLevel: 6,
championPoints: 67233,
}
];
let names = [{
championId: 19,
name: 'Warwick'
},
{
championId: 24,
name: 'Jax'
},
{
championId: 131,
name: 'Diana'
}
];
let scoresWithNames = scores.map(s => {
// find the matching championId in the names array
let name = names.find(n => n.championId === s.championId).name;
return { ...s, name };
});
console.log(scoresWithNames);
CodePudding user response:
What you want to use is Array.prototype.map
MDN. It transforms all the elements of an array using a callback function and returns the transformed array:
const champions = [
{
championId: 19,
championLevel: 7,
championPoints: 116531,
},
{
championId: 24,
championLevel: 6,
championPoints: 67710,
},
{
championId: 131,
championLevel: 6,
championPoints: 67233,
}
];
function getName(championId) {
// your logic to get the name of the champion
}
const newChampions = champions.map((c) => ({
championName: getName(c.championId),
championLevel: c.championLevel,
championPoints: c.championPoints
}));