0

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.

2
  • 3
    Currently the children are objects, not arrays. Is there a reason you did that? objects don't have a .length property, nor a dependable order. Commented Oct 31, 2018 at 15:27
  • @NicholasTower Yeah, the API is requesting that format only, so I need to append somehow elements into child but in order from 0 to n elements. Commented Oct 31, 2018 at 15:39

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.