简体   繁体   中英

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.

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/

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;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM