【问题标题】:Angular 6 compare two JSON ArraysAngular 6比较两个JSON数组
【发布时间】:2018-08-11 12:27:51
【问题描述】:

我正在使用 API 获取通知。现在是场景:

1- 我调用 API,得到 2 条记录并将它们存储在局部变量 (notifications) 中以显示在视图中。

[{"id": 1, "notification": "bla"}, {"id": 2, "notification": "bla bla"}]

2- 我每 5 秒调用一次相同的 API 来检查新通知。这次我需要将 API 响应与本地变量进行比较,所以如果记录中没有新的通知(不同的id),则不要推送本地变量,其他推送。

我尝试过这样的事情:

var val = JSON.parse(data);
if( val.length > 0 ) {
    for( var i = 0; i < val.length; i++ ) {
        this.notifications.forEach(element => {
            if( element.id != val[i].id ) {
                this.notifications.push(val[i]);
            }
        });

    }
}

但是它添加了重复的记录。任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: arrays json angular


    【解决方案1】:

    您需要使用Array.find()val 数组中查找重复对象。

    var notifications = [{"id": 1, "notification": "bla"}, {"id": 2, "notification": "bla bla"}];
    
    var data = `[{"id": 1, "notification": "bla"}, {"id": 4, "notification": "bla bla bla"}]`
    
    var val = JSON.parse(data);
    if( val.length > 0 ) {
       val.forEach((obj)=>{
         var existNotification = notifications.find(({id}) => obj.id === id);
         if(!existNotification){
           notifications.push(obj);
         }
       });
    }
    console.log(notifications);

    目前,您得到了重复的元素,因为 id 值与 notifications 数组中的所有现有 id 值进行了比较。因此,如果其中一个id 与另一个不匹配,则会立即将其推入notifications 数组。所以,更好更简单的方法是对数组使用find操作来检查现有对象。

    【讨论】:

    • 这正是我想要的。非常感谢!
    • @MuzammilVersiani 很高兴为您提供帮助 :)
    • 如果我必须比较整个数据,比如 id 和 notification 等等。在上面,您只比较数组的第一个对象,对吧?
    【解决方案2】:

    更强大的处理方法是在 JS 中使用 map

    而不是为data (size = n) 中的每个对象迭代notifications (size = m) 会导致O(m x n) 的时间复杂度更高。

    因此可以在O(n) 中完成如下:-

    var notifications = new Map();
    
    // assuming you get this at the beginning
    var data1 = `[{"id": 1, "notification": "bla"}, {"id": 2, "notification": "bla bla"}]`;
    
    checkAndAddNotification(data1);
    
    // assuming you get this at the second time
    var data2 = `[{"id": 1, "notification": "bla"}, {"id": 4, "notification": "bla bla bla"}]`
    
    checkAndAddNotification(data2);
    
    function checkAndAddNotification(data){
      var val = JSON.parse(data);
      
      if (val){
        val.forEach((obj)=>{
         var existNotification = notifications.get(obj.id);
         
         if(!existNotification){
           notifications.set(obj.id, obj);
         }
       });
      }
    }
    
    console.log(notifications);
    
    notifications.forEach((notification) => console.log(notification));

    请在运行代码时同时打开浏览器控制台。

    即使您计划在地图上进行迭代,也将按照插入对象的顺序保留顺序。 Please look here for more.

    【讨论】:

    • 这有多强大?这增加了一个额外的forEach()
    • 这就是为什么复杂性是O(n),我的朋友。我正在防止使用find() 方法引起的复杂性。如果你说的是notifications.forEach,那么这只是为了证明通知是按照它们插入的顺序。
    • @AnkitSharma 我认为你甚至不需要检查if(!existNotification),如果它已经存在,它会覆盖该值?
    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 2019-05-28
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多