最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get property value in js object when key is unknown - Stack Overflow

programmeradmin3浏览0评论

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 that a is an array, so it'd be a[i][key].p with a doubly-nested for 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
 |  Show 3 more ments

3 Answers 3

Reset to default 8

Use 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]); 
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论