如何将具有N个项目的数组转换为具有N个对象的数组

时间:2017-10-13 04:51:44

标签: javascript arrays algorithm

假设我们有一个像这样的数组:

const arr = [2,3,'red', 'white', ...]; // With n items

我想将该数组推入一个包含内部对象的数组:

[{a:2, b:3, c:'red', d:'white'}, {a: ..., b: ..., c: ...}, ...}

我从CSV文件中获取数据,这只是一个数组。我需要将这些值分配给一个对象,每个对象具有13个属性,因此每个对象将如下所示:

{ a: ..., b: ..., c: ..., d: ..., e: ..., f: ..., g: ...,
  h: ..., i: ..., j: ...., k: ..., l: ..., m: ... }, ...

我试图让这个操作变得尽可能简单,但我需要帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用嵌套for循环来完成。

const arr = [2, 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss'];

// array for storing result
var res = [];

// iterate over each 13 elements from the array
for (var i = 0, i1 = 0; i < arr.length; i += 13, i1++) {
  // define object
  res[i1] = {};

  // iterate over 13 properties a to m
  for (var j = 0; i + j < arr.length && j < 13; j++) {
    // define the property, property can be generate 
    // using radix 36(which includes 0 to 9  and a to z)
    // where a to m is within ( 10 to 22 )
    res[i1][(j + 10).toString(36)] = arr[i + j];
  }
}


console.log(res);

答案 1 :(得分:1)

如果你想避免嵌套循环:

const arr = [2, 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss', 3, 'red', 'white', 'ss'];

resultArray = [];
tempObject = [];

for(i = 0; i < arr.length; i++) {
    // Get a letter to use as a key
    newKey = String.fromCharCode(97 + (i % 26));

    // Push that onto the object
    temp_obj[newKey] = arr[i];

    // If you've done 13, put that into the array
    if((i + 1) % 13 == 0) {
        res_array.push(temp_obj);
        temp_obj = {};
    }
}