How to handle undefined in functional calls gracefully

example: get the properties of an object in an array of objects according to id

const stage = [
        { id: 0, name: "a" },
        { id: 1, name: "b" },
        { id: 2, name: "c" },
        { id: 3, name: "d" },
        { id: 4, name: "e" },
        ]

// 1:
// :find()undefinedname
let name = stage.find(v => v.id ===id).name

// 2:
// :
let name = stage.find(v => v.id ===id) ? stage.find(v => v.id ===id).name : "";

// 3:
// :
let find = stage.find(v => v.id ===id)
let name = find && find.name

expectation

it is hoped that all method calls can be done in one line like method 1, while avoiding the problem of errors caused by intermediate methods returning undefined.


Deconstruction assignment + default parameter + | value:

let  {name='-'} = stage.find(v => v.id ===8)||{}

stage.find on the right (v = > v.id = 8) | {} returns the found object or an empty object
on the left let {name} deconstructing assignment has the characteristics of soft failure . If the right side is not found resulting in an empty object on the right, name is undefined
but there is a default value on the left, so if it is not found, the result of name is < code.

({name='-'}=stage.find(v => v.id ===1)||{})
console.log(name) // b

({name='-'}=stage.find(v => v.id ===1)||{})
console.log(name) // '-'

wrapper, borrowing Maybe


from functional programming.

the idea of @ followWinter can be further simplified

.
(stage.find(v => v.id === text) || {}).name

//  undefined 
(stage.find(v => v.id === text) || {}).name || ''
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e495b5-27266.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e495b5-27266.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?