Javascript 使用下划线将两个键和值数组合并到一个对象中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12199051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
merge two arrays of keys and values to an object using underscore
提问by Cristi Mihai
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?
您将如何仅使用 underscore.js 方法将其转换为对象?
{
foo: '1',
bar: '2',
qux: '3'
}
I'm not looking for a plain javascript answer (like this).
我不是在寻找一个简单的 javascript 答案(像这样)。
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?
我问这是个人练习。我认为下划线有一种方法可以做到这一点,结果却发现它没有,这让我想知道是否可以做到。我有一个答案,但它涉及相当多的操作。你会怎么做?
采纳答案by Vikram Deshmukh
What you need to use is the _.objectmethod 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.
你需要用到的是underscore js的_.object方法。如果您的 underscore.js 版本中不存在对象方法,则您必须手动添加此方法。
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>
回答by ghirlekar
I know you asked for Underscore.js solutions, but you don't need it for this. Here's a oneliner using ES7 object spread operator and dynamic keys.
我知道你要求 Underscore.js 解决方案,但你不需要它。这是一个使用 ES7 对象扩展运算符和动态键的 oneliner。
keys.reduce((obj, k, i) => ({...obj, [k]: values[i] }), {})
回答by Tudor Morar
Using ES6:
使用 ES6:
let numbers = [1, 2, 3],
names = ["John", "Mike", "Colin"];
let a = Object.assign({}, ...numbers.map((n, index) => ({[n]: names[index]})))
console.log(a);
回答by KooiInc
How about:
怎么样:
keys = ['foo', 'bar', 'qux'];
values = ['1', '2', '3'];
some = {};
_.each(keys,function(k,i){some[k] = values[i];});
To be complete: another approach could be:
要完整:另一种方法可能是:
_.zip(['foo', 'bar', 'qux'],['1', '2', '3'])
.map(function(v){this[v[0]]=v[1];}, some = {});
For the record, without underscore you could extend Array.prototype:
为了记录,没有下划线,你可以扩展 Array.prototype:
Array.prototype.toObj = function(values){
values = values || this.map(function(v){return true;});
var some;
this .map(function(v){return [v,this.shift()]},values)
.map(function(v){this[v[0]]=v[1];},some = {});
return some;
};
// usage
var some = ['foo', 'bar', 'qux'].toObj(['1', '2', '3']);
See jsfiddle
回答by Kevin Leary
Given that this is 4 years old, and Lodash has more or less taken the place of Underscore, I thought I would share this solution using Lodash:
鉴于这是 4 岁,Lodash 或多或少取代了 Underscore,我想我会使用 Lodash 分享这个解决方案:
var keys = ['foo', 'bar', 'qux'];
var values = ['1', '2', '3'];
var obj = _.zipObject( keys, values );
Simple and clean.
简单干净。
回答by capipo
var toObj = (ks, vs) => ks.reduce((o,k,i)=> {o[k] = vs[i]; return o;}, {});
var keys=['one', 'two', 'three'],
values = [1, 2, 3];
var obj = toObj(keys, values);
console.log(obj);
回答by capipo
Cleanest is
最干净的是
keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']
function Arr2object(keys, vals) {
return keys.reduce(
function(prev, val, i) {
prev[val] = vals[i];
return prev;
}, {}
);
}
console.log(Arr2object(keys, values));
Or, use _.reduce
, but if you're using underscore you already have _.object
.
或者,使用_.reduce
,但如果您使用下划线,则您已经有了_.object
.
回答by Richard Heath
What you are looking for is the zip function.
您正在寻找的是 zip 功能。
Edit: It doesn't create an object but it does combine the array by creating a sub array
编辑:它不创建一个对象,但它确实通过创建一个子数组来组合数组
There's no function that exactly does what you want. But you can use the result of zip to create your object.
没有任何功能可以完全满足您的要求。但是您可以使用 zip 的结果来创建您的对象。
var arr = _.zip(['foo', 'bar', 'qux'], ['1', '2', '3']);
var i, len = arr.length;
var new_obj = [];
for(i=0; i<len; ++i)
new_obj[arr[i][0]] = arr[i][1];