简体   繁体   English

比较具有相同对象的 2 个 JSON 文件

[英]Compare 2 jSON files with same objects

So I have 2 jSON files, both with same set up and same objects, difference is one has old data that is not updated, the other one has real-time data that is updated in real time, I'd like to subtract the old data with the new data, and output the result.所以我有 2 个 jSON 文件,都具有相同的设置和相同的对象,区别在于一个没有更新的旧数据,另一个有实时更新的实时数据,我想减去旧的data 与新数据,并输出结果。

Code I used that ISN'T successful:我使用的代码不成功:

jQuery.getJSON(liveDataURL, function(liveData){

    jQuery.getJSON(oldDataURL, function(oldData){

        liveData.sort(function(a, b){
             return a.number - b.number;
        }).reverse();
        oldData.sort(function(a, b){
             return a.number - b.number; 
        }).reverse();

        var newList = liveData.number - oldData.number;
        console.log(newList);
    });

Any help is appreciated!任何帮助表示赞赏!

What do you mean by subtract?你说的减法是什么意思?

a = {foo: 17, bar: 12, baz: false} b = {foo: 17, bar: 10} a = {foo: 17, bar: 12, baz: false} b = {foo: 17, bar: 10}

what does "a - b" mean? “a - b”是什么意思?

Assuming:假设:

"a - b" := {bar: 12, baz: false} "a - b" := {bar: 12, baz: false}

Something like this will work:像这样的事情会起作用:

const delta = (a, b) => {
  const d = {};
  Object.keys(a).forEach(key => {
    if (typeof a[key] === 'object') {
      d[key] = delta(a[key], b[key] || {});
      if (d[key] === undefined) {
        delete d[key];
      }
    } else {
      if (a[key] !== b[key]) {
        d[key] = a[key];
      }
    }
  });
  return Object.keys(d).length ? d : undefined;
};
var newList = liveData.number - oldData.number;

This is the wrong way to find difference between list.这是查找列表之间差异的错误方法。 Just do this, if you want to find the difference of numbers只要这样做,如果你想找到数字的差异

Assuming the length of both list is same.假设两个列表的长度相同。

var newList = [];
for (var i = 0; i < liveData.length; i++){
    newList.append(liveData[i].number - oldData[i].number);
}

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

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