简体   繁体   English

在 JavaScript 中将平面数组 [k1,v1,k2,v2] 转换为对象 {k1:v1,k2:v2}?

[英]Convert flat array [k1,v1,k2,v2] to object {k1:v1,k2:v2} in JavaScript?

Is there a simple way in javascript to take a flat array and convert into an object with the even-indexed members of the array as properties and odd-indexed members as corresponding values (analgous to ruby's Hash[*array] )?在javascript中是否有一种简单的方法来获取一个平面数组并将其转换为一个对象,其中数组的偶数索引成员作为属性,奇数索引成员作为相应的值(类似于ruby的Hash[*array] )?

For example, if I have this:例如,如果我有这个:

[ 'a', 'b', 'c', 'd', 'e', 'f' ]

Then I want this:然后我想要这个:

{ 'a': 'b', 'c': 'd', 'e': 'f' }

The best I've come up with so far seems more verbose than it has to be:到目前为止我想出的最好的似乎比它必须的更冗长:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
var obj = {};
for (var i = 0, len = arr.length; i < len; i += 2) {
    obj[arr[i]] = arr[i + 1];
}
// obj => { 'a': 'b', 'c': 'd', 'e': 'f' }

Is there a better, less verbose, or more elegant way to do this?有没有更好、更简洁或更优雅的方法来做到这一点? (Or I have just been programming in ruby too much lately?) (或者我最近用 ruby​​ 编程太多了?)

I'm looking for an answer in vanilla javascript, but would also be interested if there is a better way to do this if using undercore.js or jQuery .我正在寻找 vanilla javascript 中的答案,但如果使用undercore.jsjQuery有更好的方法来做到这一点,我也会感兴趣。 Performance is not really a concern.性能并不是真正的问题。

Pretty sure this will work and is shorter:很确定这会起作用并且更短:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
var obj = {};
while (arr.length) {
    obj[arr.shift()] = arr.shift();
}

See shift() .请参阅shift()

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
var obj = arr.reduce( function( ret, value, i, values ) {

    if( i % 2 === 0 ) ret[ value ] = values[ i + 1 ];
    return ret;

}, { } );

If you need it multiple times you can also add a method to the Array.prototype:如果您多次需要它,您还可以向 Array.prototype 添加一个方法:

Array.prototype.to_object = function () {
  var obj = {};
  for(var i = 0; i < this.length; i += 2) {
    obj[this[i]] = this[i + 1]; 
  }
  return obj
};

var a = [ 'a', 'b', 'c', 'd', 'e', 'f' ];

a.to_object();    // => { 'a': 'b', 'c': 'd', 'e': 'f' }

You could first chunk your array into groups of two:您可以先将数组分成两组:

[['a', 'b'], ['c', 'd'], ['e', 'f']]

so that is is in a valid format to be used by Object.fromEntries() , which will build your object for you:所以这是Object.fromEntries()使用的有效格式,它将为您构建您的对象:

 const chunk = (arr, size) => arr.length ? [arr.slice(0, size), ...chunk(arr.slice(size), size)] : []; const arr = ['a', 'b', 'c', 'd', 'e', 'f']; const res = Object.fromEntries(chunk(arr, 2)); console.log(res); // {a: "b", c: "d", e: "f"}

With underscore.js and lodash, you don't need to implement the chunk() method yourself, and can instead use _.chunk() , a method built into both libraries.使用 underscore.js 和 lodash,您不需要自己实现chunk()方法,而是可以使用_.chunk() ,这是两个库中内置的方法。 The full lodash equivalent of the above would be:上面的完整 lodash 等效项将是:

// lodash
> _.fromPairs(_.chunk(arr, 2)); 
> {a: "b", c: "d", e: "f"}

Using _.fromPairs provides better browser support, so if using lodash, it is preferred over Object.fromEntries()使用_.fromPairs提供更好的浏览器支持,所以如果使用 lodash,它比Object.fromEntries()更受欢迎

Similarly, we can use _.object() if you're using underscore.js to build the object:同样,如果您使用 underscore.js 来构建对象,我们可以使用_.object()

// underscore.js
> _.object(_.chunk(arr, 2));
> {a: "b", c: "d", e: "f"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM