且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将多维数组转换为对象

更新时间:2023-02-14 12:42:51

你可以迭代在数组中的项目,然后递归如果找到的项目本身是一个数组(检查使用 Array.isArray

You can iterate over the items in the array and then recurse if the located item is itself an array (check using Array.isArray)

function populateFromArray(array) {
  var output = {};
  array.forEach(function(item, index) {
    if (!item) return;
    if (Array.isArray(item)) {
      output[index] = populateFromArray(item);
    } else {
      output[index] = item;
    }
  });
  return output;
}

console.log(populateFromArray(input));

这导致:

[object Object] {
  6: [object Object] {
    10: "player1"
  },
  7: [object Object] {
    5: "player2"
  }
}

查看工作jsBin

注意:你当然可以用更少的代码来做到这一点,但是代码并不总是更好!

Note: you can certainly do this in less code but less code is not always better!