gpt4 book ai didi

javascript - 实现 json 迭代

转载 作者:行者123 更新时间:2023-12-02 19:29:37 25 4
gpt4 key购买 nike

我有以下 JSON,需要迭代“规则”对象。我似乎永远无法正确地调用它,以便能够访问不仅仅是最后一条规则。

如果有人能指出我正确的方向,我将不胜感激

var rules = [{
"rule":[{
"fields":["CASE.PROSECUTED_FLAG","CASE.RESTITUTION_SIGNED"],
"conditions":["N","Y"],
"actions":"required",
"action_fields":["test1","test2"]
}],
"rule":[{
"fields":["CASE.PROSECUTED_FLAG","CASE.RESTITUTION_SIGNED"],
"conditions":["N","N"],
"actions": "required",
"action_fields": ["test3", "test4"]
}],
"rule":[{
"fields":["CASE.PROSECUTED_FLAG"],
"conditions":["Y"],
"actions": "required",
"action_fields": ["test5"]
}]
}];




function rulesControl() {
alert(rules.length);
for (var rule in rules) {

var xfields = rules[rule].rule.fields;
var conditions = rules[rule].rule.conditions;
var actions = rules[rule].rule.actions;
var action_fields = rules[rule].rule.action_fields;

//test the fields (if success, mark them, else clear them)
if (validateRule(xfields, conditions)) {
rulesAction(actions, action_fields);
} else {
ruleActionMakeClear(action_fields);
}
}
}

最佳答案

这是因为 JSON 的格式很奇怪。它在包含对象上定义了三次属性“规则”,本质上是覆盖自身。这可能更符合您的需求,而不是将所有这些单个项目数组嵌套在对象中。

var rules = [
{"rule":
{
"fields":["CASE.PROSECUTED_FLAG","CASE.RESTITUTION_SIGNED"],
"conditions":["N","Y"],
"actions":"required",
"action_fields":["test1","test2"]
}
},
{"rule":
{
"fields":["CASE.PROSECUTED_FLAG","CASE.RESTITUTION_SIGNED"],
"conditions":["N","N"],
"actions": "required",
"action_fields": ["test3", "test4"]
}
},
{"rule":
{
"fields":["CASE.PROSECUTED_FLAG"],
"conditions":["Y"],
"actions": "required",
"action_fields": ["test5"]
}
}
];

您可以通过以下方式访问它:

rules[i].rule.PROPERTY

其中 i 是规则的索引值,PROPERTY 是字段、条件等。

关于javascript - 实现 json 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11676577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com