modifying Array and outputting the modified version

I want to output all the arrays with modified version, I want to put ? in the end of usernames and ! in the end of items
const array = [
{
username: "john",
team: "red",
score: 5,
items: ["ball", "book", "pen"]
},
{
username: "becky",
team: "blue",
score: 10,
items: ["tape", "backpack", "pen"]
},
{
username: "susy",
team: "red",
score: 55,
items: ["ball", "eraser", "pen"]
},
{
username: "tyson",
team: "green",
score: 1,
items: ["book", "pen"]
},

];


Solution:

const nArray3 = array.map(user => {
user.username = user.username.map(uName => {
return uName + "?";
})

user.items = user.items.map(item => {
return item + "!";
})
return user;
})

console.log(nArray3);
const array = [
{
username: "john",
team: "red",
score: 5,
items: ["ball", "book", "pen"]
},
{
username: "becky",
team: "blue",
score: 10,
items: ["tape", "backpack", "pen"]
},
{
username: "susy",
team: "red",
score: 55,
items: ["ball", "eraser", "pen"]
},
{
username: "tyson",
team: "green",
score: 1,
items: ["book", "pen"]
},

];


Solution:

const nArray3 = array.map(user => {
user.username = user.username.map(uName => {
return uName + "?";
})

user.items = user.items.map(item => {
return item + "!";
})
return user;
})

console.log(nArray3);
Why does it output user.username.map is not a function?
5 Replies
Jochem
Jochem2y ago
.map is a function that exists on arrays, user.username is a string
user.username = user.username.map(uName => {
return uName + "?";
})
user.username = user.username.map(uName => {
return uName + "?";
})
this should be this
user.username = user.username + "?";
user.username = user.username + "?";
Or even just this
user.username += "?";
user.username += "?";
Dev_zxc
Dev_zxc2y ago
i thought you have to loop through the username specifically like what i did on looping all through the array
Jochem
Jochem2y ago
it's just a string, there's nothing to loop over because it's a single value you technically can loop over a string if you slice it first, but that would add a ? in between every character if your array items looked like this:
{
username: ["tyson"],
team: "green",
score: 1,
items: ["book", "pen"]
},
{
username: ["tyson"],
team: "green",
score: 1,
items: ["book", "pen"]
},
that'd be different, but the way you have it now you cannot loop over the username
Dev_zxc
Dev_zxc2y ago
oh when i did the map(user) im already in the array, so thats why i cannot loop through the usernames using map, items.map(item) is working because its an array
Jochem
Jochem2y ago
well, you can't loop through the usernames using map ever, even if you just access it by using array[0].username, but yes, you're already looping over the users and that's why you have access to the username right away and correct about items.map, that works because it's an array
Want results from more Discord servers?
Add your server