Really cool solution, it does look like a charm : ) You can also extract the object value in a functional style with:
const optionalChaining = (obj, str) => (obj && str) && (() => str.split('.').reduce((o, i) => o[i], obj))();
and use like that:
const letters = { a: { b: 'c' } }; optionalChaining(letters, 'a'); // {b: "c"} optionalChaining(letters, 'a.b'); // 'c' optionalChaining(letters, 'a.b.e'); // undefined optionalChaining(letters, 'z'); // undefined
We can also extend the Object prototype to avoid some problems (dont know about how good or bad it could be in terms of design, but its possible):
Object.prototype.optionalChaining = function (str) { return str.split('.').reduce((o, i) => o[i], this); } const letters = { a: { b: 'c' } }; letters.optionalChaining('a'); // {b: "c"} letters.optionalChaining('a.b'); // 'c' letters.optionalChaining('a.b.e'); // undefined letters.optionalChaining('z'); // undefined
Clean and beauty, thanks bro
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Really cool solution, it does look like a charm : )
You can also extract the object value in a functional style with:
and use like that:
We can also extend the Object prototype to avoid some problems (dont know about how good or bad it could be in terms of design, but its possible):
Clean and beauty, thanks bro