F. Rakes F. Rakes - 3 months ago 7
Node.js Question

Assigning objects dynamically from array - best practice - nodejs javascript

What is the best practice to assign objects dynamically from the contents of an array. This is the way I'm doing it right now and it works, but it seems a bit dirty. Is the better approach to make a class like object? How would I do it in that case?
example:

var names = ["test", "foo", "bar"];
var dict = {};
// init values
names.forEach(function(n){
dict[n] = {};
dict[n].property1 = false;
dict[n].property2 = true;
dict[n].property3 = "";
});

Answer

I would create factory function to create object from array. Inside that function you can use for example Array.prototype.reduce() to initialize object:

var makeMyDict = function(arr) {
    return arr.reduce(function(r, n) {
        r[n] = {
            property1: false,
            property2: true,
            property3: ""
        };
        return r;
    }, {});
}

var names = ["test", "foo", "bar"];

var dict = makeMyDict(names);
Comments