在Javascript中删除子数组项

时间:2016-02-10 09:11:01

标签: javascript jquery arrays

如何从JavaScript / jQuery中id = 2的以下数组中删除整个子数组项?

arr = [{
    "id": 1,
    "name": "Steve"
},{
    "id": 2,
    "name": "Martin"
},{
    "id": 3,
    "name": "Short"
}]

我不确定在这种情况下如何使用grepsplice

我想要的输出是:

newArr = [{
    "id": 1,
    "name": "Steve"
},{
    "id": 3,
    "name": "Short"
}]

4 个答案:

答案 0 :(得分:7)

尝试在此背景下使用Array.prototype.filter

var arr = [ {"id":1,"name":"Steve"} , {"id":2,"name":"Martin"} , {"id":3,"name":"Short"} ];
var newArr = arr.filter(function(itm){
  return itm.id !== 2;
});

答案 1 :(得分:0)

您可以在找到id

时迭代数组并使用splice



var arr = [{"id": 1,"name": "Steve"},{"id": 2,"name": "Martin"},{"id": 3,"name": "Short"}];
for (var i=0; i<arr.length; ++i) {
    if (arr[i].id == 2) {
        arr.splice(i, 1);
    }
}
alert(JSON.stringify(arr));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

为您的问题找到明确的解决方案:

var newArr = arr.filter(function(el) { return el.id!= 2; }); 
console.log(newArr);

答案 3 :(得分:0)

我就是这样做的

    var toRemove = "2";
    var toKeep = [];
    var arr = [ {"id":1,"name":"Steve"} , {"id":2,"name":"Martin"} , {"id":3,"name":"Short"} ];

    var listOfItems = JSON.stringify(arr);

    var splitItems = listOfItems.split('},');

    for(var i = 0; i< splitItems.length; i++){

    var details = splitItems[i].split(',');

    if(details[0].split(':')[1] !== toRemove){

    var people = {id:details[0].split(':')[1], name:details[1].split(':')[1].replace('}]', '')};

    toKeep.push(people);

    }


    }

    console.log(toKeep);