简体   繁体   English

使用javascript比较多个对象

[英]Multiple objects comparison using javascript

I had a array of objects (multiple objects) and want to compare them with dynamically added objects.我有一个对象数组(多个对象)并且想将它们与动态添加的对象进行比较。

currently my code looks like目前我的代码看起来像

public compare(row) {
    for (var i = 0; i < row.length; i++) {
      var a = row[i];
      console.log(a, 'first array !!!!!!!');

      var b = row[i + 1];
      console.log(b, 'Second array !!!!!!!');

      if (a != undefined && b != undefined) {
        return JSON.stringify(a) === JSON.stringify(b);
      }
      else {
        return false;
      }

    }
  }

but I'm able to compare only first two records only .但我只能比较前两条记录。 is there a way to compare the objects dynamically using javascript.有没有办法使用javascript动态比较对象。 Thanks in Advance...提前致谢...

Your loop always returns at the end of the first loop.您的循环总是在第一个循环结束时返回。 You only want to return false inside the loop if you find a mismatch, otherwise let the loop continue.如果发现不匹配,您只想在循环内返回 false,否则让循环继续。 If it doesn't find any mismatches, then you know your objects match, and you can return true.如果它没有发现任何不匹配,那么您就知道您的对象匹配,并且您可以返回 true。

public compare(row) {
  for (var i = 0; i < row.length - 1; i++) {
    var a = row[i];
    var b = row[i + 1];
    if (!a || !b) {
      continue;
    }

    if (JSON.stringify(a) !== JSON.stringify(b)) {
      return false;
    }
  }

  return true;
}

I've also set the loop to only continue while i < row.length - 1 , since there is no element at row[row.length] .我还将循环设置为仅在i < row.length - 1继续,因为row[row.length]处没有元素。

DEMO演示

 var equal = [ { a: 1 }, undefined, { a: 1 }, { a: 1 } ]; var notEqual = [ { a: 1 }, undefined, { a: 1 }, { a: 1 }, { a: 2 } ]; function compare(row) { for (var i = 0; i < row.length - 1; i++) { var a = row[i]; var b = row[i + 1]; if (!a || !b) { continue; } if (JSON.stringify(a) !== JSON.stringify(b)) { return false; } } return true; } console.log('should be true: ', compare(equal)); console.log('should be false: ', compare(notEqual));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM