Consider two arrays. One with keys. The other with values.
Output is an object made of key/value pairs.
Is there better(performance) method to do this than:
var keys = ["some", "key", "foo", "bar"];
var values = ["this", "are", "values", "dude"];
var result = { };
for(var i = 0, len = keys.length; i < len; i++) {
result[keys[i]] = values[i];
}
console.log(result);
You can use indexOf
method of array to get corresponding value from second array eg. for key 'foo', value = values[keys.indexOf('foo')];
var keys = ["some", "key", "foo", "bar"],
values = ["this", "are", "values", "dude"],
key = 'foo',
value = values[keys.indexOf('foo')];
http://underscorejs.org used for the following
_.object(keys, values)
O(N) complexity for the build, O(1) complexity for the retrieval.. I don't believe that you can beat that if retrieval is your goal.