【问题标题】:delete JSON which match to another JSON javascript angularjs json删除与另一个 JSON 匹配的 JSON
【发布时间】:2015-11-20 02:22:42
【问题描述】:

JSON A ['711','722','733','744']

JSON B [{pid: 711, name: 'hello'},{pid: 733, name: 'world'}, {pid: 713, name: 'hello'},{pid: 744, name: ' hellosdaf'}]

尝试删除与 JSON A 匹配的数组 B。如 JSON B 711、733、744 与 JSON A 的数组匹配,我想删除它们。

我尝试了以下功能,但总是有一个或两个字符串被遗漏删除。

        angular.forEach(B, function(value, index){
              if(A.indexOf(value.pid) > -1){
             B.splice(index , 1);

        }
        });

【问题讨论】:

  • 您正在使用索引来删除条目。每当您删除一个项目时,索引都会重新排列。不要从 B 中删除,而是将不匹配的元素推送到新数组。
  • 谢谢你指出我的问题

标签: javascript arrays json angularjs


【解决方案1】:

遍历数组 A,然后使用 filter 函数过滤数组 B 并使用迭代器函数并仅返回键“pid”不匹配的函数。

for(var c of A){
  B = B.filter(function(n){
    return n.pid !== parseInt(c)
  });
}

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多