0

this.users = this.users.map(oldUser => oldUser.id === user.id ? user : oldUser);

above code is to splice in updated user's data into users object, but in the same time I also wanted to add extra property into user object, I tried

this.users = this.users.map(oldUser => {
  if(oldUser.id === user.id){
    user.updated = 'grade';
    return user
  }else{
     return oldUser
  }
});

but seeing array of object within array of object, I guess my map messed up

1
  • Your code seems to do what you describe. Please provide a working code with the error and expected output Commented May 8, 2017 at 11:48

4 Answers 4

1

A working example (where users simulate this.users and user this.user):

let users = [{id:'foo'}, {id:'bar'}];
const user = {id:'bar'};

users = users.map((oldUser) => (user.id === oldUser.id) ? Object.assign({}, oldUser, {updated:'grade'}) : oldUser);
Sign up to request clarification or add additional context in comments.

Comments

0

You may want this ( if ids are unique) :

user.updated="grade";
this.users[this.users.findIndex(u=>u.id===user.id)]=user;

Much better then remapping all users...

Comments

0

Using Array.prototype.map().

Code:

const users = [{id: 1}, {id: 2}, {id: 3}],
      user = {id: 1};
      
users.map((u) => u.id === user.id ? (u.updated = 'grade') : u);
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

I can't comment that's why I m writing in answer. map function can't be used on object. To use map function you should convert object into an array then you can use map.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.