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?
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
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);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.