如何在JavaScript中切片数组

时间:2016-02-22 23:45:24

标签: javascript arrays javascript-objects

因为抓取网站,我有一个烦人的长阵列。我想将这个数组切割成具有七个属性的对象。

我希望从中得到:

  [
  ".:j:.Junque.Shoppe",
  "Texas",
  "Liberty",
  "253",
  "0",
  "2",
  "21 minutes, 24 seconds",
  "[Neptune]",
  "Pennsylvania",
  "Liberty",
  "50",
  "0",
  "2",
  "2 minutes, 7 seconds"
  //40 more sets like this
  ]

对此:

[
   {
      name: ".:j:.Junque.Shoppe",
      system: "Texas",
      region: "Liberty",
      ping: "253",
      loss: "0",
      lag: "2",
      online: "21 minutes, 24 seconds"
   },
   {
      name: "[Neptune]"
      //(...)
   },
   //(...)
 ]

2 个答案:

答案 0 :(得分:0)

您可以使用此功能执行此操作(请注意下面代码段中显示的键数组):

function sliceToObj(original, keys) {
    if (original.length % keys.length !== 0) return false;
    var res = [];
    var obj = {};
    original.forEach(function (val, i) {
        if (i > 0 && i % keys.length === 0) {
            res.push(obj);
            obj = {};
        }
        obj[keys[i % keys.length]] = val;
    });
    res.push(obj);
    return res;
}



function sliceToObj(original, keys) {
    if (original.length % keys.length !== 0) return false;
    var res = [];
    var obj = {};
    original.forEach(function (val, i) {
        if (i > 0 && i % keys.length === 0) {
            res.push(obj);
            obj = {};
        }
        obj[keys[i % keys.length]] = val;
    });
    res.push(obj);
    return res;
}

var arr =   [
    ".:j:.Junque.Shoppe",
    "Texas",
    "Liberty",
    "253",
    "0",
    "2",
    "21 minutes, 24 seconds",
    "[Neptune]",
    "Pennsylvania",
    "Liberty",
    "50",
    "0",
    "2",
    "2 minutes, 7 seconds"
    //40 more sets like this
];
var keys = [
    'name',
    "system",
    "region",
    'ping',
    'loss',
    'lag',
    'online'
];



console.log(sliceToObj(arr, keys));




答案 1 :(得分:0)

如果它始终是7个属性并且始终按正确的顺序排列:

var parseJunk = function(arr) {
  var result = [];
  for (var i = 0; i < arr.length; i += 7) {
    var obj = {
      name: arr[i],
      system: arr[i+1],
      region: arr[i+2],
      ping: arr[i+3],
      loss: arr[i+4],
      lag: arr[i+5],
      online: arr[i+6]
    };

    result.push(obj);
  }

  return result;
}