【问题标题】:Getting values using key as a variable [duplicate]使用键作为变量获取值[重复]
【发布时间】:2020-12-03 01:47:56
【问题描述】:

我基本上是想用key作为变量。

我能够获取对象键 (c000_01),但现在我需要获取该对象 (Master) 的值。

我提供了一个 sn-p 希望能有所帮助

const data = [
          {
            "idx":"10100001",
            "name":"주인공",
            "skins":{
              "c000_01":"Master"
            },
          }
          ,{
            "idx":"10100002",
            "name":"모나",
            "skins":{
              "c001_17":"Petit Mona",
              "c001_01":"Mona",
              "c001_02":"Battlesuit Mona",
              "c001_16":"Swimsuit Mona"
            },
          }
          ,{
            "idx":"10100003",
            "name":"리자",
            "skins":{
              "c002_12":"Summer Camp Lisa",
              "c002_02":"Battlesuit Lisa",
              "c002_01":"Lisa",
              "c002_00":"Lisa"
            }
            }]
            
 for (i in data) {
    for (key in data[i].skins){
    console.log(key)
    }
  }

// what I wanted to do is

 for (i in data) {
    for (key in data[i].skins){
    
    console.log(data[i].skins.key) //I want the key to be an variable so i can get the value to show master, petit mona, mona, battle suit mona, etc etc etc)
    console.log(data[i].skins.c000_01) // I don't want to type in c000_01, I want to use the key instead
    
    }
  }

【问题讨论】:

  • 使用括号表示法:console.log(data[i].skins[key])

标签: node.js json object


【解决方案1】:
 for (i in data) {
    for (key in data[i].skins){
    console.log(data[i].skins[key])//<-----this is what you want
    }
  }

【讨论】:

  • 我已经在我的 sn-p 中尝试过,结果显示 c000_01 等,而不是值 master
  • 我知道你的要求,我会尽快更新答案。
  • 您的新解决方案有效,谢谢。
猜你喜欢
  • 2017-01-08
  • 2015-07-30
  • 2019-07-16
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 2021-12-26
相关资源
最近更新 更多