Sunday, May 19, 2024
69
rated 0 times [  76] [ 7]  / answers: 1 / hits: 35552  / 12 Years ago, thu, august 30, 2012, 12:00:00

Given two arrays, one with keys, one with values:



keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']


How would you convert it to an object, by only using underscore.js methods?



{
foo: '1',
bar: '2',
qux: '3'
}


I'm not looking for a plain javascript answer (like this).



I'm asking this as a personal exercise. I thought underscore had a method that was doing exactly this, only to find out it doesn't, and that got me wondering if it could be done.
I have an answer, but it involves quite a few operations. How would you do it?


More From » underscore.js

 Answers
11

What you need to use is the _.object method of underscore js.
If object method is not present in your version of underscore.js then you will have to manually add this method to it.





keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, l = list.length; i < l; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};

console.log(_.object(keys, values))

<script src=https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js></script>




[#83333] Wednesday, August 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deonkalvinw

Total Points: 409
Total Questions: 96
Total Answers: 89

Location: Saint Pierre and Miquelon
Member since Sun, Nov 27, 2022
2 Years ago
deonkalvinw questions
Sun, Feb 6, 22, 00:00, 2 Years ago
Tue, Dec 28, 21, 00:00, 2 Years ago
Sun, Aug 22, 21, 00:00, 3 Years ago
Sun, Mar 7, 21, 00:00, 3 Years ago
;