如何在两个数组对象之间获得差异项?

时间:2014-09-15 09:15:22

标签: javascript

这里我有两个数组,但它们不是简单数组。参见下文:

var a = [{"id":1,"in":1,"num":3000},{"id":2,"in":1,"num":1500},{"id":3,"in":1,"num":1000}]
var b = [{"id":1,"in":0,"num":1000},{"id":2,"in":0,"num":1000}]

for (var i = a.length - 1; i >= 0; i--) {
     for (var j =b.length - 1; j >= 0; j--) {
        if( a[i]['id'] == b[j]['id']){
             a[i]['rest'] = a[i]['num'] - b[j]['num']
         }
      }
 }
 console.log(a)

但是我无法获得id 3,因为id 3不在b数组中。请帮忙。

这是我想要的答案

a = [
   {"id":1,"in":1,"num":3000,"rest":2000},
   {"id":2,"in":1,"num":1500,"rest":500},
   {"id":3,"in":1,"num":1000,"rest":1000}
]

THK

2 个答案:

答案 0 :(得分:1)

所以你想减去数字'在b中来自相应的数字'在for 的每个元素?不只是迭代a并检查它是否也包含在b:

var a = [{"id":1,"in":1,"num":3000},{"id":2,"in":1,"num":1500},{"id":3,"in":1,"num":1000}]
var b = [{"id":1,"in":0,"num":1000},{"id":2,"in":0,"num":1000}]

for (var i = a.length - 1; i >= 0; i--) {
  a[i]['rest'] = a[i]['num'];
  for (var j =b.length - 1; j >= 0; j--) {
    if( a[i]['id'] == b[j]['id']){
     a[i]['rest'] = a[i]['num'] - b[j]['num'];
     break;
    }
  }
}

答案 1 :(得分:1)

您可以为flag添加一些变量,以了解您是否拥有相同的id,这是您的代码示例

var flag;
var a = [{"id":1,"in":1,"num":3000},{"id":2,"in":1,"num":1500},{"id":3,"in":1,"num":1000}]
var b = [{"id":1,"in":0,"num":1000},{"id":2,"in":0,"num":1000}]

for (var i = a.length - 1; i >= 0; i--)
    flag = false;
    for (var j =b.length - 1; j >= 0; j--) {
        if( a[i]['id'] == b[j]['id']){
            a[i]['rest'] = a[i]['num'] - b[j]['num']
            flag = true;
        }
    }
    if(!flag) {
        a[i]['rest'] = a[i]['num']
    }
}