0

In one of my projects I'm using API to get data from other website but to get all of the data I would need to write 8 blocks of the same code just with two diffrent variables. So obviously I want to define function and use it.

Function takes two arguments, one is object and other one is id. Inside the function I loop through the object to get all of the data I need using object.length. Loop gets executed inside function definition and I get Uncaught TypeError: Cannot read property 'length' of undefined error in console.

Here's my code:

function listAll(objectProp, destination) {
    for (var i = 0; objectProp.length > i; i++ ) {
        var option = document.createElement("option");
        var value = document.createTextNode(objectProp.name);
        option.appendChild(value);
        document.getElementById(destination).appendChild(option);
    }
}

I've been looking for solution but I couldn't find the same problem. Can anyone explain it to me why it's happening?

Thanks!

Update: That's how code should look like.

function listAll(objectProp, destination) {
    if ( typeof(objectProp) != 'undefined' ) {
        for (var i = 0; objectProp.length > i; i++ ) {
            var option = document.createElement("option");
            var value = document.createTextNode(objectProp[i].name);
            option.appendChild(value);
            document.getElementById(destination).appendChild(option);
        }
    }
}

Thanks for help!

zubmic
  • 77
  • 1
  • 4
  • 10
  • 4
    make sure the variable you are passing to the function is actually instantiated and is not `undefined`, log the first param to the console before calling the function – KAD Jun 08 '17 at 07:06
  • 2
    You can do a simple check `if(typeof(objectProp) != 'undefined') { }` – Milan Chheda Jun 08 '17 at 07:07
  • Thanks guys! It helped! I tried it before but then nothing was happening. It turned out I had missing letter in calling the function! – zubmic Jun 08 '17 at 07:26

1 Answers1

0

You can't get the length of an Object in JavaScript using .length. You will need to either store the data in an array or use a solution such as this one: Length of a JavaScript object

Andrew Hill
  • 2,165
  • 1
  • 26
  • 39