I have an array of objects:
a = [
{81.25: {p:81.25}},
{81.26: {p:81.26}}
]
I want to loop through array ang get value of p in each element:
for (var key in a) {
console.log(a[key]); // outputs {81.25: Object}
//How do i get p value out of the current element?
}
EDIT: sorry for misleading, I wodnt want to loop againg - thought may be some way to get first object inside current one and to get it's property p.
I have an array of objects:
a = [
{81.25: {p:81.25}},
{81.26: {p:81.26}}
]
I want to loop through array ang get value of p in each element:
for (var key in a) {
console.log(a[key]); // outputs {81.25: Object}
//How do i get p value out of the current element?
}
EDIT: sorry for misleading, I wodnt want to loop againg - thought may be some way to get first object inside current one and to get it's property p.
Share Improve this question edited Mar 13, 2014 at 14:12 Prosto Trader asked Mar 13, 2014 at 13:59 Prosto TraderProsto Trader 3,5273 gold badges33 silver badges53 bronze badges 8-
use
console.log(a[key].p);
– Mohit Pandey Commented Mar 13, 2014 at 14:03 -
@zzzzBov: when key is unknown would suggest the OP doesn't know the property is always
p
. – Matt Burland Commented Mar 13, 2014 at 14:04 - a[key].p is undefined – Prosto Trader Commented Mar 13, 2014 at 14:04
-
1
@MattBurland, OP does say that he wants to "get value of p in each element", which tells me that he knows the key is
p
, but I did misread it in thata
is an array, so it'd bea[i][key].p
with a doubly-nestedfor
loop. – zzzzBov Commented Mar 13, 2014 at 14:15 -
@zzzzBov: Read the title. It's pretty obvious in context that
p
is just a placeholder for the unknown property. – Matt Burland Commented Mar 13, 2014 at 14:35
3 Answers
Reset to default 8Use a standard for
loop for the array:
for (var i = 0; i < a.length; i++) {
if (typeof a[i] == object) { //object test
for (var key in a[i]) {
if (a[i].hasOwnProperty(key)) {
console.log(a[i][key]); //here ya go
}
}
}
}
I've found the answer.
for (var key in a) {
console.log(a[key][Object.keys(a[key])[0]].p); // 81.25
}
Parse this way,
a[0]["81.25"].p
a[1]["81.26"].p
if you using loop
for (var key in a) {
for (var key1 in a[key]) {
if (typeof a[key][key1] == "object") {
console.log(a[key][key1]);
}
}
}