可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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>
回答2:
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.
keys.reduce((obj, k, i) => ({...obj, [k]: values[i] }), {})
回答3:
Using ES6:
let numbers = [1, 2, 3],
names = ["John", "Mike", "Colin"];
let a = Object.assign({}, ...numbers.map((n, index) => ({[n]: names[index]})))
console.log(a);
回答4:
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.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
回答5:
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:
var keys = ['foo', 'bar', 'qux'];
var values = ['1', '2', '3'];
var obj = _.zipObject( keys, values );
Simple and clean.
回答6:
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);
回答7:
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
.
回答8:
What you are looking for is the zip function.
zip function
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.
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];