-1

I want to loop through an array of objects and i am unable to find the key's of each object. What am i doing wrong?

The Javascript / jQuery code:

var position = [];

$('.box').each(function(){

var id = $(this).attr('id');

var offset = $(this).offset();

var offsetX = offset.left;

var offsetY = offset.top;

position.push('{"id":'+id+',"offX":'+offsetX+',"offY":'+offsetY+'}');

});

for (var i = 0; i < position.length; i++) {
  console.log(position[i].id); // i get the error of undefined
}

Html markup:

<div id="parent">

    <div class="box" id="1">1</div>
    <div class="box" id="2">2</div>
    <div class="box" id="3">3</div>
    <div class="box" id="4">4</div>
    <div class="box" id="5">5</div>
    <div class="box" id="6">6</div>
    <div class="box" id="7">7</div>
    <div class="box" id="8">8</div>
    <div class="box" id="9">9</div>
    <div class="box" id="10">10</div>

</div> 

Here the jsfiddle

billo
  • 33
  • 1
  • 1
  • 8
  • 1
    Works fine http://jsfiddle.net/v4rshzrt/. Also, don't name it `Array`, it is an object provided by JS already. PascalCase is the convention for constructors, everything else should be camelCased. – elclanrs Mar 31 '15 at 00:36
  • `Array` is a builtin type constructor. – Vinay Mar 31 '15 at 00:37
  • `Array` is the array constructor for arrays in javascript. Redefining it may make all sort of things go wrong. – slebetman Mar 31 '15 at 00:37
  • funny, copy paste this code and completely works. – Aizen Mar 31 '15 at 00:39
  • `undefined` is not an error here, it's the natural result of accessing `.id` on a string. – Bergi Mar 31 '15 at 00:53

3 Answers3

1
position.push('{"id":'+id+',"offX":'+offsetX+',"offY":'+offsetY+'}');

Well, that's not an object but a JSON string (if you're lucky and it's valid). Use a proper object literal:

position.push({"id":id, "offX":offsetX, "offY":offsetY});

and then you will be able to access its .id property.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You are adding a string to the array. You want to add an object.

position.push({id: id,offX: offsetX,offY: offsetY});
nickles80
  • 1,101
  • 8
  • 10
0

I have had a look at your code and it seems that the problem lies with your statement:

$('.box').each(function(){});

Even tho the syntax is correct there can be other problems that cause this to happen. Here are a few suggestions that might be wrong with it:

  • There is a missing JQuery file that you are referencing Or that you have not referenced a file at all.

Make sure you have the JQuery file for home testing/ServerTesting found on this site: Click Here

  • Make sure you have referenced the JQuery file in your script:
script src="jquery-1.11.2.min.js"
  • If you are not running html 5 then make sure to add:
script type="javascript/text"
Cornelis
  • 1,065
  • 8
  • 23