在JavaScript中将数组转换为对象

时间:2015-09-28 00:45:59

标签: javascript arrays refactoring javascript-objects

从数组创建一个比这个更优雅的方法?

var createObject = function(){
var myArray= generateArray();
var myObject = {
    question : myArray[0],
    answerA : myArray[1],
    answerB : myArray[2],
    answerC : myArray[3],
    answerD : myArray[4]
    };
return myObject;
}

4 个答案:

答案 0 :(得分:1)

你的背景是什么?蟒?

 var values = generateArray();
 var obj = {};
 ["question", "answerA", "answerB", "answerC", "answerD"].forEach(function(item, idx) {
     obj[item] = values[idx];
 });

 return obj;

答案 1 :(得分:0)

您可以定义属性映射:

var createObject = function(){
    // The map should have the attribute names set in order defined in `myArray`
    var map = ["question", "answerA", "answerB", "answerC", "answerD"]
    var myArray = generateArray();
    var myObject = {};
    for(var i in map)
        myObject[map[i]] = myArray[i];
    return myObject;
}

答案 2 :(得分:0)

请尝试超越'A''B''C''D'

  function arrayToObject ( array ) {
    return array.reduce(
      function ( object, cell, index ) {
        if (index > 0) object['answer' + String.fromCharCode(64 + index)] = cell;
        else           object['question'] = cell;
        return object;
      }, {}
    );
  }

答案 3 :(得分:0)

如果你想拥有一个以数组作为参数的函数,并返回一个对象,我就是这样做的:

var toObject = function(arr) {
  var newObj = {};

  for(var i = 0; i < arr.length; i++) {
    newObj[i] = arr[i];
  }
  return newObj;
};

但是,请记住,Javascript数组只是具有更多可用方法的对象,例如push()pop()和length属性。

希望这有帮助!