JavaScript / jQuery:比较2个jSON对象并将结果输出到新对象中

时间:2017-10-11 17:16:10

标签: javascript jquery json oop javascript-objects

我有一个用更新的jSON对象回复的api调用,我还有一个静态jSON对象文件。我试图比较每个团队的对象中具有相同名称的值。

因此,如果John团队在旧文件中有22个,现在有28个,那么新对象应该输出Team John为6.减去2并显示差异。

我已经制作了一个帮助理解和更新的jsFiddle。

最新更新:答案已由mscdeveloper解决了!检查他的帖子和答案如下。

UPDATE(不是答案):我在stackoverflow中搜索时找到了一个解决方案,这确实是我想要的,但是我在这个过程中失去了团队的名字,怎么能我将代码修复到它没有删除的地方,我知道它与我拥有的groupByTypeID函数有关吗?

更新了jsFiddle: https://jsfiddle.net/kqmfsz9n/5/

   var obj1 = {
    "teams": [
    {
      name: 'Test 1',
      numMembers: '50'
    },
    {
      name: 'Test 2',
      numMembers: '12'
    }
  ]
};

var obj2 = {
    "teams": [
    {
      name: 'Test 1',
      numMembers: '75'
    },
    {
      name: 'Test 2',
      numMembers: '18'
    }
  ]
};

var newObj = {};
function groupByTypeID(arr) {
    var groupBy = {};
  jQuery.each(arr, function () {
    groupBy[this.name] = parseInt(this.numMembers);
  });
  return groupBy;
}

var userArrayGroups = groupByTypeID(obj2.teams);
var origArrayGroups = groupByTypeID(obj1.teams);

var newObj = [];
for (var prop in userArrayGroups) {
  newObj[prop] = userArrayGroups[prop] - origArrayGroups[prop];
  newObj.push(userArrayGroups[prop] - origArrayGroups[prop]);
  if (newObj[prop] == 0) {
    delete newObj[prop];
  }
}

console.log(newObj);

感谢所有帮助! 谢谢。

1 个答案:

答案 0 :(得分:1)

    var obj1 = {
        "teams": [
        {
          name: 'Test 1',
          numMembers: '50'
        },
        {
          name: 'Test 2',
          numMembers: '12'
        }
      ]
    };

    var obj2 = {
        "teams": [
        {
          name: 'Test 1',
          numMembers: '75'
        },
        {
          name: 'Test 2',
          numMembers: '18'
        }
      ]
    };

    var newObj = {};
var items_arr=[];    //array of obj2 not exist in obj1

  if(obj1.teams){             //if exist array of teams obj1
     var o1teams = obj1.teams;
     if(obj2.teams){        //if exist array of teams obj2
        var o2teams = obj2.teams;
        for(var key2 in o2teams){
           var o2teams = obj2.teams;
           for(var key1 in o1teams){
                   if(o2teams[key2].name==o1teams[key1].name){
                       var numMembers_o1_int=parseInt(o1teams[key1].numMembers)||0;
                       var numMembers_o2_int=parseInt(o2teams[key2].numMembers)||0;
                       var result_numMembers_int=numMembers_o2_int-numMembers_o1_int;
                       var result_numMembers=result_numMembers_int+'';  //convert to string
                       var items_for_add=o1teams[key1];
                       items_for_add.numMembers=result_numMembers;
                       items_arr.push(items_for_add);
                   }
            }
        }
      }
  }
  newObj.items=items_arr;

  console.log(newObj);

https://jsfiddle.net/mscdeveloper/uxv1t2a7/3/