1

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.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103

3 Answers3

2

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/

zerkms
  • 249,484
  • 69
  • 436
  • 539
1

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}
nettux
  • 5,270
  • 2
  • 23
  • 33
  • Why do you test if `keys` is an array? Can't the function just require that it be an array in order to work properly? It's not like it does anything useful if `keys` isn't an array. – jfriend00 May 21 '14 at 00:05
  • What happens if *keys* has missing members, e.g. `['foo',,'bar']`? (you get a property called 'undefined'). – RobG May 21 '14 at 00:16
  • @jfriend00 No JavaScript is not statically typed. You can *require* arguments to be specific types using a variety of extensions (or just do what I've done) but you can't require it in C style. see: http://stackoverflow.com/questions/8407622/set-type-for-function-parameters – nettux May 21 '14 at 10:32
  • @nettux443 - that's not what I'm saying. Do you test the type of every single argument of every single function you write? I don't understand why it is necessary to test to see if it's an array. Further, do you know that `instanceof` won't work if you're using any cross window code and operating on an array from another window. – jfriend00 May 21 '14 at 14:49
  • @jfriend00 Yes I do. Testing variable types is absolutely necessary. The above code prevents errors if someone thought to pass in something other than an array. Feel free to suggest an improved way to check inputs. – nettux May 21 '14 at 16:48
  • @nettux443 - it also hides from the developer that they're calling your function wrong by silently doing nothing if they call the function wrong. Wouldn't it be better if it throws an exception or causes a runtime error so the developer finds right away that they are using your function wrong the first time they try to use it. The disadvantage of JS is that you sometimes have to find misuse errors in testing at runtime, not that you can silently hide them. – jfriend00 May 21 '14 at 16:53
  • @jfriend00 a fair point but even so you definitely don't want to just assume that inputs are what you expect them to be. That's bad practice and insecure if this is running server-side. I've changed the function to return false on dodgy inputs. – nettux May 21 '14 at 16:59
0
function someFunction(arr, defval)
{
  var resultObj = {};
  arr.forEach(function(el) { resultObj[el] = defval; });
  return resultObj;
}
Dan Korn
  • 1,274
  • 9
  • 14
  • Please also provide further explanation what this code does. Just a piece of code usually isn't enough. – Joeytje50 May 21 '14 at 00:03
  • It does exactly what the question asks, specifically, it "will take an array and a default value and produce an object with each array element as a key pointing to the default value." – Dan Korn May 21 '14 at 16:26
  • The Array.forEach function is documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach In this case, the Array.forEach function takes a callback function which is called with a parameter for each element of the array, and adds a property with the name of that array element and the specified default value to the result object. – Dan Korn May 21 '14 at 16:28