【问题标题】:Splice or Remove list of elements from JSON Array从 JSON 数组拼接或删除元素列表
【发布时间】:2017-04-29 00:27:59
【问题描述】:

我有一个这样的 REST API 的 JSON 数组输出,我正在使用 ng-repeat 在 HTML 上显示这些项目。

var searchresponse = [{
    "items": [{
        "employeeId": "ABC",
        "type": "D",
        "alive": "Yes"

    }, {
        "employeeId": "DEF",
        "type": "D",
        "alive": "Yes"

    }, {
        "employeeId": "NPK",
        "type": "D",
        "alive": "Yes"

    }, {
        "employeeId": "PKN",
        "type": "A",
        "alive": "Yes"
    }],
    "more": false
}];

当用户尝试使用 selectall/single select 删除时,我正在调用 REST API 以从 db 中删除员工 ID。一旦我得到一个成功的响应,我计划拼接/删除用户从视图中选择的值。我想从搜索响应中删除以下employeeid 及其类型,alive 删除

 var data1=["ABC","NPK"];

无论 data1 有什么对应的细节,都应该从 searchresponse 中删除

【问题讨论】:

标签: javascript jquery angularjs arrays json


【解决方案1】:

您只需使用splice 方法从employeeId 在data1 中的items 数组中删除每个项目。

参考资料

var searchresponse = [{
    "items": [{
        "employeeId": "ABC",
        "type": "D",
        "alive": "Yes"

    }, {
        "employeeId": "DEF",
        "type": "D",
        "alive": "Yes"

    }, {
        "employeeId": "NPK",
        "type": "D",
        "alive": "Yes"

    }, {
        "employeeId": "PKN",
        "type": "A",
        "alive": "Yes"
    }],
    "more": false
}];
var data1=["ABC","DEF"];
var items=searchresponse[0].items;
var i=items.length;
while (i--) {
    if(data1.indexOf(items[i].employeeId)!=-1){
        items.splice(i,1);
    }
}
console.log(searchresponse[0].items);

【讨论】:

  • 我试过了,它没有进入 for 循环。我有什么遗漏吗
  • searchresponse[0].items 的长度可能为 0。
  • 你确定searchresponse 看起来像你的帖子吗?
  • 这是 console.log 打印的 Array[1] 0:Object $$hashKey:"object:16" employeeId:"ABC" alive:"YES" type:"D" selected:false
  • 成功了!!我直接在 scoperesponse 中设置项目值。所以我将项目分配给范围响应并且它起作用了。非常感谢
猜你喜欢
  • 2017-05-01
  • 1970-01-01
  • 2010-10-04
  • 2023-01-23
  • 2013-06-13
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
相关资源
最近更新 更多