Make Leaf

Given an object and an array of properties to represent a path, set a leaf value

by doug65536

JavaScript

function makeLeaf(obj, path, value) {
    var lastref;
    $.each(path, function () {
        var child = obj[this];
        if (child === undefined) {
            child = {};
            obj[this] = child;
        }
        lastref = obj;
        obj = child;
    });
    lastref[path[path.length-1]] = value;
}

var $scope = {};
var t;
makeLeaf($scope, ['tree', 'b', 'c', 'd'], 10);
makeLeaf($scope, ['other', 'z', 'y', 'x'], 15);
makeLeaf($scope, ['other', 'z', 'y', 'w'], 20);

console.log($scope);

$('body').append($('<p>').text($scope.tree.b.c.d));
$('body').append($('<p>').text($scope.other.z.y.x));
$('body').append($('<p>').text($scope.other.z.y.w));