Home > Blockchain >  Write a function which editUser if the user exist in the users array?
Write a function which editUser if the user exist in the users array?

Time:04-16

I am using the array.map higher order function with a ternary operator to check the condition. I am not familiar with the method Object.assign

I tried a solution for the question, but it gives no return in the console, please verify and rectify my approach.

   const users = [
        {
            name:'Brook', 
            scores:75,
            skills:['HTM', 'CSS', 'JS'],
            age:16
        },
        {
            name:'Alex', 
            scores:80,
            skills:['HTM', 'CSS', 'JS'],
            age:18
        }, 
        {
            name:'David', 
            scores:75,
            skills:['HTM', 'CSS'],
            age:22
        }, 
        {
            name:'John', 
            scores:85,
            skills:['HTM'],
            age:25
        },
        {
            name:'Sara',
            scores:95,
            skills:['HTM', 'CSS', 'JS'],
            age: 26
        },
        {
            name:'Martha', 
            scores:80,
            skills:['HTM', 'CSS', 'JS'],
            age:18
        },
        {
            name:'Thomas',
            scores:90,
            skills:['HTM', 'CSS', 'JS'],
            age:20
        }
        ]

My solution: (NodeJS)

const editUser = (users, userUpdate) => {
    return users.map((user) => user.name == userUpdate ? Object.assign(user, { scores: userUpdate.scores, skills: userUpdate.skills, age: userUpdate.age }) : user);
}

Execution:

const userUpdate = {
    name: 'Alex',
    scores: 88,
    skills: ['HTM', 'CSS', 'JS', 'FullStack'],
    age: 20
}
console.log(editUser(users, userUpdate));

CodePudding user response:

userUpdate is object that contain name property and must be compair user.name with userUpdate.name

in this problem you compair object with name and is not equal.

const editUser = (users, userUpdate) => {
    return users.map((user) => user.name == userUpdate.name ? Object.assign(user, { scores: userUpdate.scores, skills: userUpdate.skills, age: userUpdate.age }) : user);
};
  • Related