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

标签 javascript json

我正在为 discord 机器人制作一个帮助命令,现在我正在尝试从一个 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 确实输出了正确数量的命令。

最佳答案

其中 i 指的是一个用于迭代的数字,它不是实际的 key 。因此,保留一个包含键的数组,并在循环中使用索引获取键值。

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.values 使其更简单, Array#forEach , Arrow functionDestructuring assignment .

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

关于javascript - 按列表中的编号/顺序查找 json 对象中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55872103/

相关文章:

Javascript - 如何从 Accordion 中获取值到表单中

javascript - Firebase 函数发送后无法设置 header

json - 如何使用 jq 获取 json 流的嵌套键

javascript - 当我在浏览器上按回时如何重置单选按钮

javascript - 事件类默认为标签列表

json - 在读取 json 数据时动态识别对象的类型

html - Typescript 获取 JSON 对象

arrays - 震动 : Make Nested Make a nested array as part of main array

C# 使用 XmlReader 获取额外的空白值,但不使用 XmlDocument

javascript - 与商店 : Cannot read property 'state' of undefined (pure-react-carousel)