Milos Petrovic
Milos Petrovic

Reputation: 193

How to get the length of an Object

I have this array and I want to append some new items on click, but first of all I need to get the length of array in order to add the item on right place. This is how array looks like:

"parent": [{
   "child": {}, 
   "child2": {},
   ...
 }];

Array needs to look exactly like this and it's empty on page load. I want to insert values in child elements for example:

"parent": [{
    "child": {
       "0": 1,
       "1": 1,
       "2": 1
     },
     ...
 }];

First of all on start I cannot get length of child array :(

Note that array must look exactly like this and child elements should be in array order from 0 to n.

Everytime I ask for child length I get "undefined" as response. Even if I put manually value ex. "child": {"0": "1", "1": "1"} i got undefined as child length.

Upvotes: 0

Views: 484

Answers (2)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

This isn't an array, but an object whose properties are "0", "N"...

Either refactor this to use an actual array or do this:

const length = Object.keys (o.parent[0].child).length

...which may include these and other own object's properties, so it's not reliable for your purpose...

There's no definitive solution if you don't want to use arrays.

Approach to make this more reliable

If your input has these objects instead of arrays, you might want to convert them to arrays, and then operate on them!

Here's a code snippet which defines objectToArray and produces an array for keys that can be converted into numbers:

const o = { '0': 'hello', '1': 'world', '2': '!!!' }

const objectToArray = o => Object.entries (o)
                            .filter (([key]) => !isNaN (key))
                            .reduce ((array, [key, value]) => 
                                (array[Number (key)] = value, array),
                                []
                             )

const output = objectToArray (o)

console.log (output)

Upvotes: 0

ferhado
ferhado

Reputation: 2594

Objects don't have a length, you will need to use Object.key like in example:

let array = {
  "parent": [{
    "child": {
      "0": 1,
      "1": 1,
      "2": 1
    }
  }]
};


console.log(Object.keys(array.parent[0].child).length);

Upvotes: 1

Related Questions