在JavaScript中将变量的值调用为对象的属性

时间:2019-07-19 01:31:28

标签: javascript node.js json

我正在为此应用程序编写命令处理程序,该应用程序使用嵌套的JSON键/值列表作为执行命令的目录。 (文件的结构仍在进行中):

{
    "commands": {
        "category1": {
            "command1_c1": {
                "alias": ["c1c1alias1", "c1c1alias2", "c1c1alias3", "c1c1alias4"]
            },
            "command2_c1": {
                "alias": ["c1c2alias1", "c1c2alias2"]
            },
            "command3_c1": {
                "alias": ["c1c3alias1", "c1c3alias2"]
            }
        },
        "category2": {
            "command1_c2": {
                "alias": ["c2c1alias1", "c2c1alias2"]
            },
            "command2_c2": {
                "alias": ["c2c2alias1"]
            }
        }
    }
}

此JSON文件在我的JavaScript文件中“必需”:

const jsonCommands = require("./commands/commands.json");

我编写了这段代码,应该像这样遍历每个级别,然后根据用户输入来定位命令:

for (var listedCategory in jsonCommands.commands) {
    console.log(`listedCategory: ${listedCategory}`);
    for (var listedCommand in jsonCommands.commands.listedCategory) {
        console.log(`listedCommand: ${listedCommand}`);
        if (listedCommand === userCommand) {
            console.log(`success in finding command ${userCommand}`);
        }
    }
}

上面的代码在第二个for-in循环中不记录任何内容。上面编写的代码的返回结果是这样(并且不会引发错误):

listedCategory: lookup
listedCategory: other

这是该代码的另一个版本,其功能相似,但也访问alias数组。我怀疑它现在是否会返回任何数组值:

Object.keys(jsonCommands).forEach(category => {
    console.log(`Category: ${category}`);
    Object.keys(jsonCommands.category).forEach(command => {
        console.log(`Command: ${command}`);
        if (command === userCommand) {
            console.log(`A command was recognized: \`${userCommand}\``);
        } else {
            Object.keys(jsonCommands.category.command).forEach(aliasCommand => {
                console.log(`aliasCommand: ${aliasCommand}`);
                if (aliasCommand === userCommand) {
                    console.log(`A command alias was recognized: \`${userCommand}\``);
                }
            });
        }
    });
});

上面的代码也不起作用。这是引发的错误:

Object.keys(jsonCommands.category).forEach(command => {
TypeError: Cannot convert undefined or null to object

现在,我在这里看到两个问题,每个示例一个。 (尽管我主要发布了第二个示例,以显示我还尝试了其他方法。)第一个代码示例中的问题是,它可能试图将变量名作为JSON键而不是在JSON中分配的变量名来访问。回调,例如在语句jsonCommands.commands.listedCategory中,使返回值不确定,这就是为什么它不会迭代的原因。

我不确定第二个代码示例中发生了什么。我怀疑引发错误的原因是相似的-告诉Object.keys访问未定义的值。

但是,我确定,如果该错误已修复,第一个解决方案将可以正常工作。我将如何使在回调中声明的变量listedCategory的值用作JSON对象的属性?

很抱歉,如果这是一个重复的问题。

2 个答案:

答案 0 :(得分:0)

TL:DR;

要使用变量访问属性时,需要使用[]

let jsonCommands = {"commands": {"category1": {"command1_c1": {"alias": ["c1c1alias1", "c1c1alias2", "c1c1alias3", "c1c1alias4"]},"command2_c1": {"alias": ["c1c2alias1", "c1c2alias2"]},"command3_c1": {"alias": ["c1c3alias1", "c1c3alias2"]}},"category2": {"command1_c2": {"alias": ["c2c1alias1", "c2c1alias2"]},"command2_c2": {"alias": ["c2c2alias1"]}}}}

let userCommand = 'command2_c2'

for (var listedCategory in jsonCommands.commands) {
    console.log(`listedCategory: ${listedCategory}`);
    for (var listedCommand in jsonCommands.commands[listedCategory]) {
        console.log(`listedCommand: ${listedCommand}`);
        if (listedCommand === userCommand) {
            console.log(`success in finding command ${userCommand}`);
        }
    }
}

答案 1 :(得分:0)

您应该像这样编写第一段代码:


let userCommand = 'command3_c1'

for (const listedCategory in jsonCommands.commands) {
    console.log(`listedCategory: ${listedCategory}`);
    for (const listedCommand in jsonCommands.commands[listedCategory]) {
        console.log(`listedCommand: ${listedCommand}`);
        if (listedCommand === userCommand) {
            console.log(`success in finding command ${userCommand}`);
        }
    }
}```

And the out is:

```Category: commands
Command: category1
aliasCommand: command1_c1
aliasCommand: command2_c1
aliasCommand: command3_c1
A command alias was recognized: `command3_c1`
Command: category2
aliasCommand: command1_c2
aliasCommand: command2_c2

第二个:


let userCommand = 'command3_c1'

Object.keys(jsonCommands).forEach(category => {
    console.log(`Category: ${category}`)
    Object.keys(jsonCommands[category]).forEach(command => {
        console.log(`Command: ${command}`)
        if (command === userCommand) {
            console.log(`A command was recognized: \`${userCommand}\``)
        } else {
            Object.keys(jsonCommands[category][command]).forEach(aliasCommand => {
                console.log(`aliasCommand: ${aliasCommand}`)
                if (aliasCommand === userCommand) {
                    console.log(`A command alias was recognized: \`${userCommand}\``)
                }
            })
        }
    })
})

结果是:

Command: category1
aliasCommand: command1_c1
aliasCommand: command2_c1
aliasCommand: command3_c1
A command alias was recognized: `command3_c1`
Command: category2
aliasCommand: command1_c2
aliasCommand: command2_c2