18

Is there a common Javascript/Coffeescript-specific idiom I can use to accomplish this? Mainly out of curiosity.

I have two arrays, one consisting of the desired keys and the other one consisting of the desired values, and I want to merge this in to an object.

keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
Jorge Israel Peña
  • 36,800
  • 16
  • 93
  • 123
  • 1
    JavaScript doesn't have associative arrays. Object members can be accessed in an array-like syntax, but they are still objects. – nikc.org Aug 03 '11 at 05:24
  • 1
    @nikc: Thanks, I realize that. But given the context I felt like 'associative array' would've communicated what I was going for in less words. – Jorge Israel Peña Aug 03 '11 at 05:27
  • @Jorge - just call it an object, 'cos that's what javascript has. Less to type too. ;-) – RobG Aug 03 '11 at 05:30

3 Answers3

27

var r = {},
    i,
    keys = ['one', 'two', 'three'],
    values = ['a', 'b', 'c'];

for (let i = 0; i < keys.length; i++) {
    r[keys[i]] = values[i];
}

console.log(r);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Henke
  • 4,445
  • 3
  • 31
  • 44
bjornd
  • 22,397
  • 4
  • 57
  • 73
7
keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']

d = {}

for i, index in keys
    d[i] = values[index]

Explanation: In coffeescript you can iterate an array and get each item and its position on the array, or index. So you can then use this index to assign keys and values to a new object.

OverZealous
  • 39,252
  • 15
  • 98
  • 100
6

As long as the two arrays are the same length, you can do this:

var hash = {};
var keys = ['one', 'two', 'three']
var values = ['a', 'b', 'c']

for (var i = 0; i < keys.length; i++)
    hash[keys[i]] = values[i];

console.log(hash['one'])
console.log(hash.two);
Chris
  • 4,393
  • 1
  • 27
  • 33