Value check in nested javascript object (might not exist)

Value check in nested javascript object (might not exist)



Is there an elegant and concise way to avoid doing something like this to check a value deep within an object member hierarchy in javascript?



enter image description here





Please include code as text and not as image.
– t.niese
Aug 26 at 17:26






Possible duplicate of Test for existence of nested JavaScript object key
– t.niese
Aug 26 at 17:47




3 Answers
3



There is currently no concise way to do it in plain JavaScript, unless you use a helper function or a third-party library.



There is a proposal (at Stage 1 as of August 2018) to add the ?. operator to JavaScript which does exactly what you want.


?.



With that proposal accepted, you would be able to use ?. instead of . anywhere where a property might be missing, so your code would become:


?.


.


// careful: this syntax is not available yet
var hasDisplay = handlerInput.requestEnvelope.context?.System?.device?.supportedInterfaces?.Display



This is cheating, but you can use the _.get function from Lodash


_.get


_.get(validations, "path.to.nested.prop");



From the docs



Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.





I guess he was asking if he could just check the nested value without using dots(a.b.c.d.e.f.g.h) and you did that only just with lodash.
– NAVIN
Aug 26 at 17:38





I disagree. He wants to do it in one line. That's what you _.get
– seebiscuit
Aug 26 at 17:47


_.get



I wrote an NPM module that allows you to query by a string path.



https://www.npmjs.com/package/js-path-resolver
http://www.twelvetone.tv/docs/developer-tools/npm-modules/js-path-resolver



Here's a codepen
https://codepen.io/Flamenco/pen/xaVKjR/?editors=1111



For your use case:


import resolver from 'js-path-resolver'
const info = resolver(handlerInput, 'requestEnvelope.context.System.device.supportedInterface.Display', onError:'continue')
const hasDisplay = info.exists
const display = info.get()



In a nutshell, you split the string, then try to resolve the path, one string at a time. There are all sorts of issues implementing this, such as escaping dots, handling array indexes, etc, so using a library makes life much easier. In this library, you can also set, and delete the resolved path.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế