使用下划线将两个键和值数组合并到一个对象 [英] merge two arrays of keys and values to an object using underscore
问题描述
给定两个数组,一个带键,一个带值:
Given two arrays, one with keys, one with values:
keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']
如何将它转换为一个对象 仅使用underscore.js方法 ?
How would you convert it to an object, by only using underscore.js methods?
{
foo: '1',
bar: '2',
qux: '3'
}
我不是在寻找一个简单的javascript答案(像这样)。
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?
推荐答案
你需要使用的是 _。object 下划线js的方法。
如果您的underscore.js版本中没有对象方法,那么您必须手动将此方法添加到它。
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>
这篇关于使用下划线将两个键和值数组合并到一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!