在列表中按编号/顺序查找json对象中的元素

时间:2019-04-26 17:02:22

标签: javascript json

我正在为不和谐的机器人制作帮助命令,现在我正试图从json文件中获取所有命令的列表。

json文件如下:

{
    "command": {
      "help": {
        "name": "help",
        "syntax": "help str",
        "description": "Outputs list of commands or info on a specific command.",
        "example": ">>help, >>help gn"
      },
      "gn": {
        "name": "gn",
        "syntax": "gn int",
        "description": "gn, guess number. Used to guess the secret number, if you get it correct you gain 1 point.",
        "example": ">>gn 22"
      }
    }
  }

我正在尝试的代码:

jsonobject = JSON.parse(bufferFile('\command.json'));
if (!input[1]) {
    console.log(Object.keys(jsonobject.command).length);
    for (var i = 0; i < Object.keys(jsonobject.command).length; i++) {
        message.channel.send(jsonobject.command[i].description);            
    }
}

这应该输出每个命令的描述,但是jsonobject.command[i]undefined。我尝试输出jsonobject.command,得到[object Object]Object.keys(jsonobject.command).length确实输出了正确数量的命令。

2 个答案:

答案 0 :(得分:1)

i是指用于迭代的数字,而不是实际的密钥。因此,请保留包含键的数组,并在循环内使用索引获取键值。

jsonobject = JSON.parse(bufferFile('\command.json'));

if (!input[1]) {
    // heys array
    var keys = Object.keys(jsonobject.command);
    for (var i = 0; i < keys.length; i++) {
        message.channel.send(jsonobject.command[keys[i]].description);            
        // get key from keys array using index --^^^^^----
    }
}

使用ES6,您可以使用Object.valuesArray#forEachArrow functionDestructuring assignment使其更简单。

if (!input[1]) {
    Object.values(jsonobject.command).forEach(({description}) => message.channel.send(description))
}

答案 1 :(得分:0)

第一个答案让我震惊不已,这已经很好地解释了您的问题。无论如何,这是使用for ... of的另一种方法(Internet Explorer不支持,但所有现代浏览器均不支持)。

var jsonobject = {
    "command": {
      "help": {
        "name": "help",
        "syntax": "help str",
        "description": "Outputs list of commands or info on a specific command.",
        "example": ">>help, >>help gn"
      },
      "gn": {
        "name": "gn",
        "syntax": "gn int",
        "description": "gn, guess number. Used to guess the secret number, if you get it correct you gain 1 point.",
        "example": ">>gn 22"
      }
    }
  }

for (var key of Object.keys(jsonobject.command)) {
    console.log(key + ': ' + jsonobject.command[key].description);            
}