If you have ever needed to set some values of a dictionary in JavaScript or PHP, then you know that you have to do something like myArray[a][b][c] = 0. But what if we don’t know that the subkeys will be “a->b->c” until runtime? You would need a way to index into the dictionary dynamically and return the resulting modified dictionary. Below are code snippets in JavaScript and PHP that do exactly that.

JavaScript

// Call me like var myNewArray = myArray.deepSetDictionaryValues("a", "b", "c", value);
Object.defineProperty(Object.prototype, "deepSetDictionaryValues", {
    value: function() {
        arguments = Array.prototype.slice.call(arguments);
        var value= arguments[arguments.length - 1];
        arguments = arguments.slice(0,-1);

        var o = this;
        var returner = o;
        for (var i = 0; i < arguments.length - 1; i++) {
            var n = arguments[i];
            if (n in o) {
                o = o[n];
            } else {
                o[n] = {};
                o = o[n];
            }
        }
        var n = arguments[arguments.length - 1];
        o[n] = value;
        return returner;
    },
    enumerable: false
});

PHP

/*
 * Call me like $myNewArray = deepSetDictionaryValues($myArray, ["a","b","c"], $value);
 */
public static function deepSetDictionaryValues($dict, $keyHierarchy, $value){
    $o = &$dict;
    for($i = 0; $i < count($keyHierarchy) - 1; $i++){
        $subKeyAtI = $keyHierarchy[$i];
        if(array_key_exists($subKeyAtI, $o)){
            $o = &$o[$subKeyAtI];
        }
        else{
            $o[$subKeyAtI] = [];
            $o = &$o[$subKeyAtI];
        }
    }

    $o[$keyHierarchy[count($keyHierarchy) - 1]] = $value;

    return $dict;
}

Leave a Reply