简体   繁体   中英

How to set an initial value for an object key?

I have an object, where the user is an object, and firstly I check from an array if one of it's elements equals to the criteria. It's not always the case, and if it doesn't exist in the array, I want to return an empty object (instead of undefined ):

//...
return {
  user: users.find(user => user.uid === selectedUser)
}

You can use the Logical OR ( || ) operator. This will return the first truthy value it encounters. This means that if the find() returns undefined it will return the value on the right side of the || .

return {
  user: users.find(user => user.uid === selectedUser) || {}
}

You can see an example here:

 function findUser(selectedUser) { const users = [{ uid: 1, name: 'John' }, { uid: 2, name: 'Doe' }]; return { user: users.find(user => user.uid === selectedUser) || {} } } console.log(findUser(1)); console.log(findUser(2)); console.log(findUser(3)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM