1

I want something along the lines of array1.length from the below array:

var array1 = {
 sub1: [1,2,3],
 sub2: ["K","J","H"],
 sub3: ["Mango","Armada","Leffen","Mew2king"],
 sub4: ['1/8"', '3/16"', '1/4"'],
};

Right now I'm getting the following outputs:

console.log(array1) //Object {sub1: Array[3], sub2: Array[3]...}
console.log(array1.length) //undefined
console.log(array1[1]) //undefined
console.log(array1[1].length //Cannot read property 'length' of undefined

Where am I going wrong?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Matthew Sirkin
  • 93
  • 2
  • 14

6 Answers6

1

array1 not is a array, is a object. sub1 and so on are arrays, then you can:

array1.sub1.length; // returns 3
BrTkCa
  • 4,703
  • 3
  • 24
  • 45
1

You have an Object, not an Array.

You could iterate over the keys and get the length of the arrays inside of the object.

var object = { sub1: [1, 2, 3], sub2: ["K", "J", "H"], sub3: ["Mango", "Armada", "Leffen", "Mew2king"], sub4: ['1/8"', '3/16"', '1/4"'] };
Object.keys(object).forEach(function (key) {
    console.log(object[key].length);
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    But Object.keys is not supported in IE8 and below, Opera and FF 3.6 and below. – Sankar Oct 24 '16 at 13:06
  • you could use [`for ... in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop with a check for [`hasOwnProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) – Nina Scholz Oct 24 '16 at 13:10
0

Try this...

var array1 = {
  sub1: [1, 2, 3],
  sub2: ["K", "J", "H"],
  sub3: ["Mango", "Armada", "Leffen", "Mew2king"],
  sub4: ['1/8"', '3/16"', '1/4"'],
};

console.log(array1.sub1.length,array1.sub2.length,array1.sub3.length,array1.sub4.length);
Sankar
  • 6,908
  • 2
  • 30
  • 53
0

You could always do something like this:

var array1 = [[1,2,3],["K","J","H"],["Mango","Armada","Leffen","Mew2king"],
 ['1/8"', '3/16"', '1/4"']];
var flatArray = [].concat.apply([],array1)

This will flatten the array so you can use length etc.

Coss
  • 453
  • 1
  • 4
  • 12
0

See Converting JSON Object into Javascript array

var array1 = {
 sub1: [1,2,3],
 sub2: ["K","J","H"],
 sub3: ["Mango","Armada","Leffen","Mew2king"],
 sub4: ['1/8"', '3/16"', '1/4"'],
};
alert("Size : "+Object.keys(array1).map(function(k) { return array1[k] }).length);

OUTPUT

Size : 4

HOW IT WORKS

Converting the keys to an array and then mapping back the values with Array.map Then, can get the length of this array. Gg wp.

NB : You can also create a var at the beginning and then use it to all your process.

Community
  • 1
  • 1
Aks
  • 395
  • 3
  • 11
-1

array1 is a JSON object. So

array1.subArray.length

should work

Jimmy Adaro
  • 1,325
  • 15
  • 26