Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Matt's solution is pure genius - however there is some room for improvement:</p> <ul> <li>The solution fails if the 'path' has no separators; <code>set('h1', somevalue)</code> will fail because the splitting of the path fails in that case</li> <li>Only global scope is supported.</li> <li>If you have an object with <code>obj.here.is.a.value = "I am a value"</code> and you ask for <code>obj.here.is.a.value.no.value</code> - it will still return "I am a value"</li> </ul> <p>Here's my fix for these three issues:</p> <pre><code> getPropertyValueByPath : function(obj, path) { path = path.split(/[\[\]\.]+/); if(path[path.length - 1] == "") { path.pop(); }; while(path.length &amp;&amp; ( obj = obj[path.shift()])); return obj; } setPropertyValuebyPath : function(obj, path, value) { var pathElements = path.replace(/\[|\]/g, '.').replace(/\.+/g, '.').split(/\./) pathEnd = pathElements[pathElements.length - 1] pathRoot = (pathElements.slice(0, pathElements.length - 1).join('.')) var currObj = obj for(var i = 0; i &lt; pathElements.length; i++) { if( typeof (currObj[pathElements[i]]) == 'undefined') { currObj[pathElements[i]] = {} } currObj = currObj[pathElements[i]] } // This line by Matt is genious :) getPropertyValueByPath(obj, pathRoot)[pathEnd] = value return true } </code></pre> <p>call them like this:</p> <pre><code>var joe = {} setPropertyValueByPath(joe,'the[1].long.and[2].road', 'yeah') // joe.the[1].long.and[2].road now has a value of 'yeah' - // all the missing objects were created // this will alert 'yeah' alert( getPropertyValueByPath(joe,'the[1].long.and[2].road') ) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload