[Solved] Javascript associative array return TypeError


You can do something close in javascript – this function is possibly not the prettiest way to do it, but it’s generic

the first argument is the “root” object, this is followed at least 1 “nodes”, and the last argument is the value

function assoc(root) {
    var parts = arguments.slice(1);
    var value = parts.pop();
    parts.reduce(function(result, part, index) {
        if (index < parts.length - 1) {
            return result[part] = result[part] || {};
        }
        result[part] = value;
    }, root);
}

now your code needs to change like this:

var $form = {}; // use an object, not an array
for (var $i = 0; $i < 6; $i++) {
    assoc($form,5,480,'value',$i, Math.floor(Math.random() * (6 - 4 + 1)) + 4);
}
console.log(JSON.stringify($form));

solved Javascript associative array return TypeError