循环遍历数组以在Javascript中创建对象

时间:2014-09-24 17:45:25

标签: javascript arrays

我想编写一个带有数组的函数,如:

var columns = ['distance', 'times', 'acceleration']

然后从这个数组,我想生成这样的东西:

[{id: id_0, distance: 0, times: 0, acceleration: 0}, {id: id_1, distance: 1, times: 1, acceleration: 1}]

请注意,我们这里有2个对象,但我希望它是我传入参数的任何数字。这就是我所拥有的:

generateData: function(rows, columns) {
  var generatedData = [];
  for (var i = 0, rowLen = rows.length; i < rowLen; i++) {
    for (var n = 0; i < columns.length; n++) {
      // not sure how to construct an object here from looping through my columns array
      generatedData.push({
      id: 'id_ + n',
      // confused here
      });
    }
  return generatedData;
  }
}

3 个答案:

答案 0 :(得分:2)

这是动态创建自己的功能的理想场所。试试这个:

function createArrayOfObjects(columns, count) {
  var objectProps = new Array(columns.length);
  for (var i = 0; i < columns.length; i++){
    //":j" will be the variable j inside the dynamic function
    objectProps[i] = columns[i] + ":j";
  }

  var funcBody = "var arr = new Array(count);" +
      "for(var j = 0; j < count; j++){" +
          "arr[j] = {" + objectProps.join(',') + "};" +
      "}" +
      "return arr;";

  //Create a new function and call it with count as the parameter, returning the results
  return new Function("count", funcBody)(count);
}

var count = 10;
var columns = ['distance', 'times', 'acceleration'];

createArrayOfObjects(columns.concat('id'), count);

这样做的好处是只需要在其他解决方案需要嵌套循环的情况下循环遍历列数组。

JSPerf

答案 1 :(得分:1)

我告诉你最初的非优化解决方案。它取决于你做优化。

generateData: function(rows, columns) {
  var generatedData = [];
  for (var i = 0; i < rows.length; i++) {
      var myObj = {};
      myObj["id_" + i] = i;
      for (var n = 0; n < columns.length; n++) {
          myObj[columns[n]] = i;
      }
      generatedData.push(myObj);
  }
  return generatedData;
}

答案 2 :(得分:1)

一种功能方法,它将从传入的数组中获取对象属性,而不是对它们进行硬编码,在for循环中可能看起来像这样填充一个名为&#39; rows&#39;属性名称来自名为&#39; cols&#39;:

的数组的值
cols.forEach(function(cv, ci, ca) { rows[ri][cv] = ri; });

请参阅代码段以获取完整示例。请注意,在此示例中,我只是推送&#34;行&#34;的当前索引。作为属性值进入对象。

&#13;
&#13;
var columns = ['distance', 'times', 'acceleration'];

function generateData(numRows, cols) {
    rows = new Array(numRows);
    for(ri=0; ri < rows.length; ri++) {
        rows[ri] = { id: ri };
        cols.forEach(function(cv, ci, ca) {
            rows[ri][cv] = ri;
        });
    }
    return rows;
}


data = generateData(5, columns);
console.log(data);
&#13;
&#13;
&#13;