在javascript错误中比较数组

时间:2016-04-07 01:18:19

标签: javascript json

我试图比较2个json值列表。如果比较结果为true,则不显示显示并仅显示语句为false的值。

以下是代码:

var files= '{"files":[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\/files\/doc1.pdf"},{"name":"doc2.pdf","title":"Armoogum","path":"mfpreader.comze.com\/files\/doc2.pdf"}]}';
  var result = '[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\/files\/doc1.pdf"},';

       for (var i = 0; i < files.length; i++) {
                                   var file = files[i];                 
                      for(var j=0;j<arrayResults.length;j++){   

                          if (files[i]==arrayResults[j].json.name){
                              alert("Matching found");
                            //full_list =  full_list + arrayResults[j].json.name + " " + arrayResults[j]._id + "  " + arrayResults[j].json.title + " " + arrayResults[j].json.path + '<br />';

                          }else {

                            alert("no similar files");
                             str += '<br /><div class="fileSection">' + '<br/>' + '<input class="fileName" type="hidden" value="'+ file.name + '" />' + file.name + '<br/>' + '<input class="fileTitle" type="hidden" value="'+ file.title +'" />' +  file.title + '<br/>' + '<input class="filePath" type="hidden" value="'+ file.path +'" />' + '<button onclick="add(this)">Add</button> '+  '</div><br/>' ;

                          }                           


                   }

输出结果应该只是doc2.pdf的json列表。相反,它只是显示所有列表。

如果能得到一些帮助,我将非常感激。

2 个答案:

答案 0 :(得分:0)

如果您想比较javascript中的内容,最好使用===而不使用类型转换而不是==

见这里:Equality comparisons and sameness

答案 1 :(得分:0)

有几件事需要纠正。主要是您可以使用JSON.parse()来提取数据:

&#13;
&#13;
var files= '{"files":[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\/files\/doc1.pdf"},{"name":"doc2.pdf","title":"Armoogum","path":"mfpreader.comze.com\/files\/doc2.pdf"}]}';
var result = '[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\/files\/doc1.pdf"}]';

// you need to convert the above strings to arrays:
files = JSON.parse(files).files; // You need the files property
arrayResults = JSON.parse(result);

for (var i = 0; i < files.length; i++) {
    var file = files[i];
    for(var j=0;j<arrayResults.length;j++){
        // note the name property on the files[i] object:
        if (files[i].name===arrayResults[j].name){ 
            alert("Matching found for " + files[i].name);
        }else {
            alert("no similar files for " + files[i].name);
        }
    }  
}
&#13;
&#13;
&#13;