I need to assign idNumber of all participants to idNumbers. Can you please check my code?
const participants = [
{ name: 'Abu', idNumber: 'S7282395H', gender: 'male' },
{ name: 'Mary', idNumber: 'T4689018Z', gender: 'female' },
{ name: 'Suzi', idNumber: 'G5512873T', gender: 'female' },
{ name: 'T Chakra', idNumber: 'T8198514B', gender: 'male' }
];
// pass a function to map
const getIds= participants.map((name) => `${participants.name} ${participants.idNumber}`);
console.log(getIds);
You should be referencing name and not participants inside the map:
const participants = [
{ name: 'Abu', idNumber: 'S7282395H', gender: 'male' },
{ name: 'Mary', idNumber: 'T4689018Z', gender: 'female' },
{ name: 'Suzi', idNumber: 'G5512873T', gender: 'female' },
{ name: 'T Chakra', idNumber: 'T8198514B', gender: 'male' }
];
// pass a function to map
const getIds= participants.map((name) => `${name.name} ${name.idNumber}`);
console.log(getIds);
If you just want an array of idNumber then you can use map like this
const participants = [
{ name: 'Abu', idNumber: 'S7282395H', gender: 'male' },
{ name: 'Mary', idNumber: 'T4689018Z', gender: 'female' },
{ name: 'Suzi', idNumber: 'G5512873T', gender: 'female' },
{ name: 'T Chakra', idNumber: 'T8198514B', gender: 'male' }];
const getIds = participants.map(participant => participant.idNumber);
console.log(getIds);
If you want an array of strings containing the name and the idNumber you can use string interpolation for that.
const participants = [
{ name: 'Abu', idNumber: 'S7282395H', gender: 'male' },
{ name: 'Mary', idNumber: 'T4689018Z', gender: 'female' },
{ name: 'Suzi', idNumber: 'G5512873T', gender: 'female' },
{ name: 'T Chakra', idNumber: 'T8198514B', gender: 'male' }];
const getIds = participants.map(participant => `${participant.name} ${participant.idNumber}`);
console.log(getIds);
Hmm I'm not sure if this is exactly what you want, but it sounds like you want to get an array of all participant idNumber values. In that case, perhaps something like this?
const idNumbers = participants.map((participant) => participant.idNumber));
In your code inside the map callback, you're currently trying to access name and idNumber from participants, which will return undefined since participants is an array and doesn't have those props. What you want to do is access these props in each individual participant from the callback argument.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map