[英]Is there a function to make an object given an array of keys and a default value in JavaScript
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.
我只是想知道一个内置的东西,比如python的默认字典。
There is one! 有一个! And by accident it has the exact
someFunction
name!!! 而且偶然它有一些确切的
someFunction
名称!
function someFunction(arr, value) {
return arr.reduce(function(result, key) {
result[key] = value;
return result;
}, {});
}
JSFiddle: http://jsfiddle.net/VH8Wr/ JSFiddle: http : //jsfiddle.net/VH8Wr/
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}
function someFunction(arr, defval)
{
var resultObj = {};
arr.forEach(function(el) { resultObj[el] = defval; });
return resultObj;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.