如何对数组元素进行分组

时间:2018-09-12 12:43:02

标签: javascript

我有一个数组:

var arr = ['User1','123456','User2','456789','User3','546544'];

如何获取这样的对象数组:

var arr2 = [{name: 'User1', id: 123456},{name: 'User2', id: 456789}, {name: 'User3', id: 546544}];

我尝试过:

arr.forEach(function (item, i, arr) {
            arr2.push(
                {
                    name: arr[i],
                    id: arr[i + 2]
                }
            );
        });

4 个答案:

答案 0 :(得分:0)

以一种简单的方式,您需要做两件事:

  1. 检查长度是否均匀。
  2. 按两次循环数两次,按需进行推送。

var arr = ['User1', '123456', 'User2', '456789', 'User3', '546544'];
var arrObj = [];
if (arr.length % 2 === 0)
  for (var i = 0; i < arr.length; i += 2)
    arrObj.push({
      "name": arr[i],
      "id": parseInt(arr[i + 1], 10),
    });
console.log(arrObj);

答案 1 :(得分:0)

查看代码中的注释。

const arr = ['User1', '123456', 'User2', '456789', 'User3', '546544'];

// Ok, so what you to do is to group the infos and create a new object
// There is many function you can use, in the following example, I will use
// Array.reduce

// We gonna call couple, two values that goes together, like :
// User1 and 123456
// User2 and 456789

// ...
const ret = arr.reduce((tmp, x, xi) => {
  // Add nothing for the first value of the couple
  // We gonna ignore, User1, User2 and User3
  if (xi % 2 === 0) return tmp;

  return [
    ...tmp,

    // Add a new value in the array
    {
      // The name is the first value of the couple
      name: arr[xi - 1],

      // The id is the second value of the couple
      id: x,
    },
  ];
}, []);

console.log(ret);

答案 2 :(得分:-1)

for循环可在所有计算机的所有版本上使用,并具有能够直接跳过索引的附加优点,forEach只能用很多额外的代码来完成。另外forEach比for循环慢。

var arr1 = ['User1', '123456', 'User2', '456789', 'User3', '546544'], arr2 = [];
for (var i = 0; i < arr1.length - 1; i += 2) { // here is the i+=2
  arr2.push({
    "name": arr1[i],
    "user": arr1[i + 1] // here is the i+1
  });
}
console.log(arr2)

或更短数组

var arr1 = ['User1', '123456', 'User2', '456789', 'User3', '546544'], arr2 = [];
for (var i = 0; i < arr1.length - 1; i += 2) {
  arr2.push({
    [arr1[i]]: arr1[i + 1]
  });
}
console.log(arr2)

答案 3 :(得分:-1)

您的问题的解决方案如下:

var arr2 = [];

for (var i = 0; i < arr.length; i = i + 2) {
   arr2.push({name : arr[i], id: arr[i + 1]})
}

下次尝试显示您的试用代码时,您将以这种方式获得更多的进步。