safe-access
safe-access copied to clipboard
Does bracket notation work?
var obj = {
'bracket:string': 'This string must be accessed with brackets'
}
obj['bracket:string']
//'This string must be accessed with brackets'
access(obj, "['bracket:string']")
//undefined
It doesn't look like it unless I'm doing something incorrectly here. Any help would be appreciated. Thanks!
Bracket notation doesn't work, but internally, safe-access uses bracket notation and the strings that you pass in to safely access properties, so you can do this:
var obj = {
'bracket:string': 'This string must be accessed with brackets'
};
access(obj, 'bracket:string');
For deeply nested objects, you can simply use dot notation:
var obj = {
'bracket:string': {
'str@nge-symbols': 'This string must also be accessed with brackets'
}
};
access(obj, 'bracket:string.str@nge-symbols');
This workaround will not work when a property name will have a '.' in the name. So, it will be useful to have bracket notation.
Thanks!
Agree with @galusben. From server we receive objects like:
{ attributes: { 'product.displayName': 'A product' } }