簡體   English   中英

比較循環中的兩個json數組

[英]Compare two json arrays in loop

我有以下兩個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
    }
}

我想檢查optionAlternatives中是否存在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

使用JSON.NET。 您可以輕松地將json字符串解析為JArray,並使用for循環可以比較值。

我不確定我是否完全理解,但是這是我建議您使用偽代碼解決的方法。

for each object in optionText
  id = object.id
  filteredAlternatives = QuestionAlternatives.filter(question.id === id)
  if(filteredAlternatives.length > 0) 'Id in optionText exists in QuestionAlternatives!'

查看Array.prototype.filter()

您可以使用對象/哈希表來提高這種操作的效率(盡管這會占用更多的內存):

// 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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM