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 = "";
});
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);
Your approach seems fine. You can always use reduce
to build an accumulated object.
const props = {
property1: false,
property2: true,
property3: ``
};
const names = [`foo`, `bar`, `baz`];
const dict = names.reduce((a, x) => {
a[x] = {};
for (let p in props) a[x][p] = props[p];
return a;
}, {});
// Or using object spread (requires babel at the moment)
const dict = names.reduce((a, x) => (a[x] = {...props}, a), {});
console.log(dict);
{ foo: { property1: false, property2: true, property3: '' },
bar: { property1: false, property2: true, property3: '' },
baz: { property1: false, property2: true, property3: '' } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.