我试图从Json Array获取下一个对象,而不使用成员名

时间:2016-06-06 09:45:36

标签: javascript jquery json

我试图获取Json数组中的下一个对象而不提及成员名称使用Javascript获取键值名称

var Commandjson = {
    "commands": {
        "MyObj.SubObj.Action.ActionEvent": {
            "Id": "MyObj.SubObj.Action.ActionEvent.CustomAction",
            "EnableRules": ["MyObj.SelectionCountExactlyOne"],
            "Actions": [{
                "ActionType": "3",
                "Attributes": {
                    "FunctionName": "MyObj.Command.close"
                },
                "Parameters": [{
                    "Name": "",
                    "ParameterName": "",
                    "ParameterType": "21",
                    "Value": "Selected"
                }]
            }]
        }
    }
};

从上面, 我试图获取AttributesParameters

我试过

Commandjson.commands[0].Actions[0].Attributes.FunctionName

但是错误是

Uncaught TypeError: Cannot read property 'Actions' of undefined(…)

请帮助我错过了。

1 个答案:

答案 0 :(得分:1)

你最好使用

Commandjson.commands['MyObj.SubObj.Action.ActionEvent'].Actions[0].Attributes.FunctionName

因为命令不是数组,而是对象或使用对象的键进行动态访问。

var Commandjson = {
    "commands": {
        "MyObj.SubObj.Action.ActionEvent": {
            "Id": "MyObj.SubObj.Action.ActionEvent.CustomAction",
            "EnableRules": ["MyObj.SelectionCountExactlyOne"],
            "Actions": [{
                "ActionType": "3",
                "Attributes": {
                    "FunctionName": "MyObj.Command.close"
                },
                "Parameters": [{
                    "Name": "",
                    "ParameterName": "",
                    "ParameterType": "21",
                    "Value": "Selected"
                }]
            }]
        }
    }
};

var commands = Object.keys(Commandjson.commands); // get all commands

console.log(Commandjson.commands[commands[0]].Actions[0].Attributes.FunctionName);