2

Have an array containing an object which contains more arrays. How can the length of the nested arrays be accessed with .length?

const array = [ { var: [ 'asd', 'a3', 'a4' ], 
                  bar: [ 'asd', 'c3', 'c4' ] } ];

When using array[0].var.length; if for example var[] only contains 1 attribute, it start measuring the string character length of the attribute. The number i'm after is the number of attributes not string length. If there are more than 1 attribute inserted then it measures the the number of attributes as it should.

anaximander
  • 357
  • 1
  • 5
  • 12
  • Is this JavaScript? Please add proper tags. – ZorgoZ Jan 19 '19 at 11:16
  • is it dynamic or the properties and nesting level is already known/fixed? – S.Serpooshan Jan 19 '19 at 11:24
  • for current code, you can simply use `array[0].var.length` and `array[0].bar.length`, both return 3 – S.Serpooshan Jan 19 '19 at 11:29
  • The strange thing is that if for example var[] only contains 1 attribute, it start measuring the string character length of the attribute. The number i'm after is the number of attributes not string length. If there are more than 1 attribute inserted then it measures the the number of attributes as it should. – anaximander Jan 19 '19 at 11:38

1 Answers1

1

If you have only one object in the array, you can use for in loop to iterate over the properties of the object and get the array associated with each key.

const array = [
                { 
                   var: [ 'asd', 'a3', 'a4' ], 
                   bar: [ 'asd', 'c3', 'c4' ]
                } 
              ];


for(let key in array[0]) {
  console.log(array[0][key].length);
}

If you have more than one objects in the array and those objects in turn have variable number of arrays in them, you can use a combination of for of and for in loop to get the lengths of all the arrays inside all the nested objects.

const array = [
                { 
                  var: [ 'asd', 'a3', 'a4' ], 
                  bar: [ 'asd', 'c3', 'c4' ]
                } 
              ];

for(let arrayItem of array) {
  for(let key in arrayItem) {
    console.log(arrayItem[key].length);
  }
}
Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • Getting the same result as mentioned in the edit. If the nested array only contains 1 item then it measures the number of chars in the string, if more than 1 item, then it measures number of items correctly. – anaximander Jan 19 '19 at 11:56
  • `If the nested array only contains 1 item then it measures the number of chars in the string` no it doesn't. It measures the length of the array associated with each key in the nested object. – Yousaf Jan 19 '19 at 11:59
  • Thats what happens in my code for some reason – anaximander Jan 19 '19 at 12:01
  • Code I posted doesn't have this problem. You haven't posted your code so I can't tell you what's wrong in your code. Try using the code I posted – Yousaf Jan 19 '19 at 12:02