从列表中获取对象的值

时间:2020-07-15 12:40:32

标签: javascript reactjs object

给出这样的列表:

[ 
  {"id": "psqIb1qoRQS9jDuSpzjk", "highscore": 10, "name": "Tom" }, 
  { "id": "xXBNYGJZqUw8zsiCnChP", "highscore": 10, "name": "John" }, 
  { "id": "Rnjxf1o3CCpS1tzgR4qs", "name": "Jakob", "highscore": 11 } 
]

我想通过索引获得这些对象之一的高分值。 逻辑建议我做类似data[2].highscore的操作(并希望收到回“ 11”),但是我收到以下错误:TypeError:无法读取未定义的属性“ highscore”。我应该如何定义高分?

示例[红色:有效]

const data = [{
    "id": "psqIb1qoRQS9jDuSpzjk",
    "highscore": 10,
    "name": "Tom"
  },
  {
    "id": "xXBNYGJZqUw8zsiCnChP",
    "highscore": 10,
    "name": "John"
  },
  {
    "id": "Rnjxf1o3CCpS1tzgR4qs",
    "name": "Jakob",
    "highscore": 11
  }
]

console.log(data[2].highscore)
console.log(data[data.length-1].highscore)

5 个答案:

答案 0 :(得分:1)

var data =  [ { "id": "psqIb1qoRQS9jDuSpzjk", "highscore": 10, "name": "Zolly" }, { "id": "xXBNYGJZqUw8zsiCnChP", "highscore": 10, "name": "gg" }, { "id": "Rnjxf1o3CCpS1tzgR4qs", "name": "gg", "highscore": 11 } ];
data.map(key => {
  if (key.highscore) {
    console.log(key.highscore)
  }
})

答案 1 :(得分:0)

如果要获取对象的值。如果对象名称是“ object”,则必须使用

object.highscore

您只使用了不正确的名称

答案 2 :(得分:0)

  1. 请检查数据中的值是对象还是字符串。
  2. 请直接尝试beginner [9] .highscore,而不考虑变量。

答案 3 :(得分:0)

如此奇怪的错误...我使用点表示法(也包括数组表示法)为您的数据创建了一个代码段,并且有效。

let data = [ { "id": "psqIb1qoRQS9jDuSpzjk", "highscore": 10, "name": "Zolly" }, { "id": "xXBNYGJZqUw8zsiCnChP", "highscore": 10, "name": "gg" }, { "id": "Rnjxf1o3CCpS1tzgR4qs", "name": "gg", "highscore": 11 } ];
let ciao = data[0];
console.log(ciao.highscore);
console.log(ciao["highscore"]);

答案 4 :(得分:0)

const beginner = [  {     "id": "psqIb1qoRQS9jDuSpzjk",     "highscore": 10,     "name": "Tom"   },   {     "id": "xXBNYGJZqUw8zsiCnChP",     "highscore": 10,     "name": "John"   },   {     "id": "Rnjxf1o3CCpS1tzgR4qs",     "name": "Jakob",     "highscore": 11   } ];

var value = beginner[1].highscore;
console.log(value);

// or 
beginner.map(data=>{ 
  console.log(data.highscore);
});