我有以下两个JSON
数组对象。
questions.QuestionAlternatives:
[{
Id: "53e169ce-acb1-4cb3-b7b9-9314a84660e0",
AlternativeText: "Opt2",
RiskScore: "1"
}, {
Id: "a1c30d1f-e585-4a74-a3a5-9f2d26fb804f",
AlternativeText: "Opt3",
RiskScore: "2"
}, {
Id: "85385ec6-a4d0-489b-bf08-b4a7321e9cfe",
AlternativeText: "Opt1",
RiskScore: "1"
}]
optionText:
[{
OptionText = "Opt2", Id = "53e169ce-acb1-4cb3-b7b9-9314a84660e0"
}, {
OptionText = "Opt3", Id = "a1c30d1f-e585-4a74-a3a5-9f2d26fb804f"
}, {
OptionText = "Opt1", Id = "85385ec6-a4d0-489b-bf08-b4a7321e9cfe"
}, {
OptionText = "opt5", Id = ""
}]
现在我想在以下代码中对此进行比较:
for (var i = 0; i < json[0].Questions.length; i++) {
if (json[0].Questions[i].Id == id) {
//Compare here
}
}
我想检查QuestionAlternatives中是否存在optionText中的Id。如果确实存在,我想用OptionText中的OptionText中的值设置OptionText。一个简单的更新。
如果它不存在,我想将带有空Id的对象添加到QuestionAlternative。
是谁能把我推向正确的方向?我试过这个比较:
for(var opt = 0; opt < optionText.length; opt++) {
for(var a = 0; a < json[0].Questions[i].QuestionAlternatives.length; a++) {
if(optionText[opt].Id == json[0].Questions[i].QuestionAlternatives[a].Id) {
console.log("exists");
} else {
console.log("does not");
}
}
}
但这给了我以下内容:
(3) exists
does not
(3) exists
does not
exists
答案 0 :(得分:0)
使用JSON.NET。您可以轻松地将json字符串解析为JArray,并使用for循环可以比较值。
答案 1 :(得分:0)
我不确定我是否完全理解,但是我建议您在伪代码中推荐它。
for each object in optionText
id = object.id
filteredAlternatives = QuestionAlternatives.filter(question.id === id)
if(filteredAlternatives.length > 0) 'Id in optionText exists in QuestionAlternatives!'
答案 2 :(得分:0)
您可以使用object / hash-table来提高此类操作的效率(尽管会使内存更加密集):
// var optionText = JSON.parse(...);
// questions.QuestionAlternatives = JSON.parse(...);
// questionAlternatives { Id => question alternative }
var questionAlternatives = {};
var questionAlternative;
for(var z = 0; z < questions.QuestionAlternatives.length; z++){
questionAlternative = questions.QuestionAlternatives[z];
questionAlternatives[questionAlternative.Id] = questionAlternative;
}
var option;
for(var z = 0; z < optionText.length; z++){
option = optionText[z];
if(questionAlternatives[option.Id]){
// found alternative
// something like this:
questionAlternatives[option.Id].OptionText = option.OptionText;
}else{
// id not found on alternatives
}
}