Reputation:
This would be the intended behaviour
a = ['foo', 'bar', 'thing', 'etc'];
b = someFunction(a, false);
b; //{'foo': false, 'bar': false, 'thing': false, 'etc': false}
Is there some function I can use that will take an array and a default value and produce an object with each array element as a key pointing to the default value?
edit: thank you all for the suggestions for writing my own. I was just wondering about a builtin, something like python's default dict.
Upvotes: 1
Views: 86
Reputation: 5406
Here is a function that will take a list of keys and a value. It creates an object and dynamically sets it's attribute names with the value provided then returns it.
function makeObj(keys, value) {
var obj = {};
if (keys instanceof Array) {
for (var i = 0; i < keys.length; i++ ) {
if (keys[i]) {
obj[keys[i]] = value;
}
}
return obj;
}
return false;
}
var a = ['foo', 'bar', 'thing', 'etc'];
var b = makeObj(a, false);
b; //{'foo': false, 'bar': false, 'thing': false, 'etc': false}
Alternatively you can make it a class (I know you asked for a function but this is what I'd do..):
function makeObj(keys, value) {
if (keys instanceof Array) {
for (var i = 0; i < keys.length; i++ ) {
if (keys[i]) {
this[keys[i]] = value;
}
}
}
}
var a = ['foo', 'bar', 'thing', 'etc'];
var b = new makeObj(a, false);
b; //{'foo': false, 'bar': false, 'thing': false, 'etc': false}
Upvotes: 1
Reputation: 1294
function someFunction(arr, defval)
{
var resultObj = {};
arr.forEach(function(el) { resultObj[el] = defval; });
return resultObj;
}
Upvotes: 0
Reputation: 254926
There is one! And by accident it has the exact someFunction
name!!!
function someFunction(arr, value) {
return arr.reduce(function(result, key) {
result[key] = value;
return result;
}, {});
}
JSFiddle: http://jsfiddle.net/VH8Wr/
Upvotes: 2