-1

Is it even possible to get length of all objects inside an array? Let say i have an array which looks like that:

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]);
    }
}

How can i correctly get total lenght of objects inside path array here?

Suttero
  • 91
  • 7

2 Answers2

1

Try to find the length of keys:

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);
}
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • How do i add them together so i will get 4? I can do path[c][0].length + path[c][1].length but i want it to be automatic. So i dont have to do it, everytime i add new array. :) – Suttero Aug 15 '18 at 04:28
  • @Suttero, you can use one variable.....I have just updated my answer...please check. – Mamun Aug 15 '18 at 04:29
  • @Suttero, you are most welcome :) – Mamun Aug 15 '18 at 04:31
1

I guess this is what you are looking for. Added count variable and incremented in the path.

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);
Ramesh
  • 2,297
  • 2
  • 20
  • 42