将数组转换为具有相应索引作为键的对象

时间:2017-11-09 13:46:03

标签: javascript arrays object lodash

这是一个非常简单的问题,但我没有找到任何答案或功能。我有一个简单的数组:

["Desc1", "Desc2", "Desc3", "Desc4", "Desc5"]

我想将它转换为这样的对象:

{0: "Desc1", 1: "Desc2", 2: "Desc3", 3: "Desc4", 4: "Desc5"}

我可以使用Lodash但不能使用ES6

6 个答案:

答案 0 :(得分:7)

这是一个简单的单行。

const a = ["Desc1", "Desc2", "Desc3", "Desc4", "Desc5"];

const r = Object.assign({}, a);

console.log(r);

答案 1 :(得分:0)

使用Array#forEach function。使用对象的键添加索引

var arr =["Desc1", "Desc2", "Desc3", "Desc4", "Desc5"];
var obj={};

arr.forEach(function(a,b){
obj[b]=a
})

console.log(obj)

答案 2 :(得分:0)

另一种方法可能是使用reduce

var output = ["Desc1", "Desc2", "Desc3", "Desc4", "Desc5"].reduce( function(a,b,i){ 
   ( a = typeof a == "string" ? {[i-1] : a} : a ), a[i] = b;
   return a; 
});
console.log( output );

答案 3 :(得分:0)

var arr =["Desc1", "Desc2", "Desc3", "Desc4", "Desc5"];
var obj = arr.reduce(function(accumulator,  currentvalue, currentindex){
   accumulator[currentindex]=currentvalue;
   return accumulator;
}, {});
console.log(obj);

答案 4 :(得分:0)

在数组上应用forEach()方法怎么样?

var obj = {} // declaring an empty object
var array = ["Desc1", "Desc2", "Desc3", "Desc4", "Desc5"] // storing the array in a variable
array.forEach(function(item, index) {
  obj[index + 1] = item; // storing the item in a property with the corresponding number
});
console.log(obj);

希望能回答你的问题:)

答案 5 :(得分:0)

您可以使用带有索引计数器的for of循环。



var array = ["Desc1", "Desc2", "Desc3", "Desc4", "Desc5"],
    i = 0;
    object = {};

for (object[i++] of array);

console.log(object);