如何从对象数组中删除项目?

时间:2011-04-12 02:59:32

标签: javascript arrays

    var arr = [
                     {id:2,date:'2010-10-03',des:'goodday'},
                     {id:3,date:'2011-02-13',des:'badday'},
                     {id:4,date:'2011-04-03',des:'niceday'}
                   ];

现在我要删除{id:3,date:'2011-02-13',des:'badday'},然后arr应该是

        var arr = [
                     {id:2,date:'2010-10-03',des:'goodday'},
                     {id:4,date:'2011-04-03',des:'niceday'}
                   ];

我该怎么办?

4 个答案:

答案 0 :(得分:15)

假设您的对象中的id字段是唯一的,您可以执行以下操作将其删除。要使用的功能是Splice

    var arr = [
        {
        id: 2,
        date: '2010-10-03',
        des: 'goodday'},
    {
        id: 3,
        date: '2011-02-13',
        des: 'badday'},
    {
        id: 4,
        date: '2011-04-03',
        des: 'niceday'}
    ];

    for(var i=0; i<arr.length; i++){
        if(arr[i].id == 3){
            arr.splice(i, 1);  //removes 1 element at position i 
            break;
        }
    }

console.log(arr);  
//should give you 
//                      var arr = [
//                               {id:2,date:'2010-10-03',des:'goodday'},
//                               {id:4,date:'2011-04-03',des:'niceday'}
//                          ];

答案 1 :(得分:1)

答案 2 :(得分:0)

arr.splice(1,1);将移除arr[1]处的对象, 并arr[2]将滑入其位置。

答案 3 :(得分:0)

您可以使用过滤方法实现相同目的:

// Your array
var oArr = [
    {id:2,date:'2010-10-03',des:'goodday'},
    {id:3,date:'2011-02-13',des:'badday'},
    {id:4,date:'2011-04-03',des:'niceday'}
];

// Array with the values to be removed, here I have taken the id
var oArrToRemove = [2] 

// Using filter method to delete the object
var oNewArr = arr.filter(ele => { return remArr.indexOf(ele.id) === -1})

// The oNewArray will be as follows
oNewArr = [
    {id:3,date:'2011-02-13',des:'badday'},
    {id:4,date:'2011-04-03',des:'niceday'}
];