简体   繁体   English

遍历数组以使用Javascript创建对象

[英]Looping through an array to create an object in Javascript

I want to write a function that takes an array such as: 我想编写一个函数,该函数需要一个数组,例如:

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

Then from this array, I want to generate something like this: 然后从这个数组,我想生成这样的东西:

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

Notice that we have 2 objects here, but I want it to be whatever number I pass in to my parameter. 请注意,这里有2个对象,但我希望它是我传递给参数的任何数字。 Here is what I have: 这是我所拥有的:

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;
  }
}

This is the perfect place to dynamically create your own function. 这是动态创建自己的函数的理想场所。 Try this: 尝试这个:

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);

This has the benefit of only having to loop over the columns array once where other solutions require nested loops. 这样做的好处是,在其他解决方案需要嵌套循环的情况下,只需循环一次column数组即可。

JSPerf JSPerf

I am giving you away the initial non-optimized solution. 我正在向您赠送最初的非优化解决方案。 Its upto you to do the optimizations. 由您决定进行优化。

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;
}

A functional approach that will take the object properties from the passed in array, instead of hard-coding them, might look something like this inside the for loop to populate an array named 'rows' with property names coming from the values of an array named 'cols': 一种功能性的方法将从传递的数组中获取对象属性,而不是对其进行硬编码,而在for循环中可能看起来像这样,以使用名称为array的值填充属性来填充名为“ rows”的数组'cols':

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

See the snippet for a full example. 有关完整示例,请参见代码段。 Note that, in this example, I'm just shoving the current index of "rows" into the object as the property value. 请注意,在此示例中,我只是将“行”的当前索引推入对象作为属性值。

 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); 

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

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