比较数组和json数据

时间:2015-12-09 13:39:03

标签: javascript arrays diff

http://jsfiddle.net/0czdrn7t/4/

我尝试比较两个数组,

在数组Type中查找对象(arrayB = 4),如果所有对象(Type = 4)PrivilegearrayA值不匹配,则插入arrayC

对于这个示例,arrayA[0]已经在arrayB最后一个对象中已经匹配,那么我不希望它推入结果,想要我的代码错了吗?

var arrayA = [1];

var arrayB = [ { Type: 1,
        Privilege: 0,
      },
      { Type: 3,
        Privilege: 0,
      },
      { Type: 3,
        Privilege: 1,
      },
      { Type: 4,
        Privilege: 1,
      } ];


var arrayC = [];

var type = 4;
for (var i = 0; i < arrayA.length; i++) {
  var insertValidate = true;
  var issetTypeValidate = false;

  for (var ii = 0; ii < arrayB.length; ii++) {
    if (arrayB[ii].Type == type) {
      if (arrayB[ii].Privilege != arrayA[i]) {
        insertValidate = false;
        // break;
      }
      
      issetTypeValidate = true;
    }
  }

  
  if (issetTypeValidate == true) {
    if (insertValidate == true) {
      var o = {};
      o.Type = type;
      o.Privilege = arrayA[i];
      arrayC.push(o);
    }
  } else {
    // var o = {};
    // o.Type = type;
    // o.Privilege = arrayA[i];
    // arrayC.push(o);
  }
}

console.log(arrayC);

2 个答案:

答案 0 :(得分:1)

因为updateRoleList[ii].Privilege != inputUserRoleType4[i]返回falseupdateRoleList[ii].Privilege等于1inputUserRoleType4[i]也是1时。

答案 1 :(得分:0)

试试这个:

      var arrayA = [1];

    var arrayB = [ { Type: 1,
            Privilege: 0,
          },
          { Type: 3,
            Privilege: 0,
          },
          { Type: 3,
            Privilege: 1,
          },
          { Type: 4,
            Privilege: 1,
          } ];


    var arrayC = [];

    var type = 4;
    for (var i = 0; i < arrayA.length; i++) {
      var insertValidate = true;
      var issetTypeValidate = false;

      for (var ii = 0; ii < arrayB.length; ii++) {
        if (arrayB[ii].Type == type) {
          if (arrayB[ii].Privilege == arrayA[i]) {
//          alert(arrayB[ii].Privilege +'='+arrayA[i])
// if at least one of them is equal, than don't print it
            insertValidate *= false;
            }
        issetTypeValidate = true;
        }
      }

      if (issetTypeValidate == true) {
        if (insertValidate == true) {
          var o = {};
          o.Type = type;
          o.Privilege = arrayA[i];
          arrayC.push(o);
        }
      } else {

      }
    }


    alert(JSON.stringify(arrayC));