0

I have a JavaScript object like:

myobj: "[
        {"id":"2027","street":"street name one"},
        {"id":"2515","street":"street name two"}
       ]"

How can I get the length and the list of keys in this object?

I've tried:

var keys = Object.keys(myobj).length;
console.log(keys);

but it always returns a length of "1"...why?

Jaime
  • 166
  • 2
  • 3
  • 15
Marco
  • 61
  • 1
  • 8

2 Answers2

2

myobj looks like it's an Array with 2 elements, which both have 2 properties. If you want the number of properties of myobj[0] use:

var myobj = [
    { "id": "2027", "street": "street name one" },
    { "id": "2515", "street": "street name two", "foo": "bar" }
];
console.log(Object.keys(myobj[0]).length); // 2
console.log(Object.keys(myobj[1]).length); // 3

Object.keys on an Array will return the same value as it's .length property.

Object.keys([ "foo", "bar", "baz"]); // 3
Halcyon
  • 57,230
  • 10
  • 89
  • 128
0

i resolved using eval.

eval('var obj='+myobj);

to get the lenght i do:

var keys = Object.keys(obj).length;
console.log(keys);

to loop through elements:

for (i = 0; i < keys; i++) {
console.log(obj[i].id);
console.log(obj[i].street);
};
Marco
  • 61
  • 1
  • 8
  • FYI, if you simply want to iterate over the elements in the array, you don't need `Object.keys` at all. Just do `for (var i = 0; obj.length; i++)`. `obj` is actually an array. – Felix Kling Aug 20 '14 at 16:57