如何正确获取数组中对象的总长度

时间:2018-08-15 04:17:42

标签: javascript

是否有可能获得数组中所有对象的长度? 假设我有一个看起来像这样的数组:

var foo = [{
    "id": 1,
    "path": {
        "1": [{
            x: 21,
            y: 22
        }, {
            x: 22,
            y: 12
        }],
        "2": [{
            x: 21,
            y: 22
        }, {
            x: 22,
            y: 12
        }]
    }
}];

for (let x in foo) {
    var path = foo[x].path;
    for (let c in path) {
        console.log(path[c]);
    }
}

如何在这里正确获取 path 数组中的对象的总长度?

2 个答案:

答案 0 :(得分:1)

尝试查找键的长度:

Object.keys(path[c]).length

var foo = [{
    "id": 1,
    "path": {
        "1": [{
            x: 21,
            y: 22
        }, {
            x: 22,
            y: 12
        }],
        "2": [{
            x: 21,
            y: 22
        }, {
            x: 22,
            y: 12
        }]
    }
}];

for (let x in foo) {
  var path = foo[x].path;
  var totalLen = 0;
  for (let c in path) {
    totalLen += Object.keys(path[c]).length;
  }
  console.log(totalLen);
}

答案 1 :(得分:1)

我想这就是您要寻找的。添加了count变量并在路径中递增。

var foo = [{
  "id": 1,
  "path": {
    "1": [{
      x: 21,
      y: 22
    }, {
      x: 22,
      y: 12
    }],
    "2": [{
      x: 21,
      y: 22
    }, {
      x: 22,
      y: 12
    }]
  }
}];
var count = 0;
for (let x in foo) {
  var path = foo[x].path;
  for (let c in path) {
    //console.log(path[c]);
    count++;
  }
}
console.log(count);