如何从数组中删除某个对象

时间:2018-08-21 18:35:44

标签: jquery

我有一个如下所示的数组

var test = 
[
  {
    "name": "Mike",
    "incentives": "23.45",
    "id": "1"
  },
  {
    "name": "Larsen",
    "incentives": "34.78",
    "id": "2"
  },
  {
    "name": "Steve",
    "incentives": "26.78",
    "id": "3"
  }
]

我要删除某个对象

我尝试如下所示

var idtoberemoved = 2

test = test.filter((obj) => typeof obj.id = '2');

https://jsfiddle.net/o2gxgz9r/65584/

4 个答案:

答案 0 :(得分:1)

您可以在数组中找到该元素的索引,然后使用拼接将其删除。

var test = [{
    "name": "Mike",
    "incentives": "23.45",
    "id": "1"
  },
  {
    "name": "Larsen",
    "incentives": "34.78",
    "id": "2"
  },
  {
    "name": "Steve",
    "incentives": "26.78",
    "id": "3"
  }
];

//Use splice to remove the element
test.splice(
  //find the index of the element to be removed
  test.indexOf(test.find(function(element){ return element.id === "2"; }))
  //remove 1 element from the index found
  , 1
);

console.log(test);

答案 1 :(得分:0)

typeof obj.id将为您提供"string",并且您想过滤出id属性不等于"2"的对象。所以应该是

test.filter(obj => obj.id !== '2');

在JS中,=用于分配,而不用于相等性测试。我们使用=====!==!=进行相等性测试。 =====之间是有区别的,但这是一个整体。

答案 2 :(得分:0)

    var test = [
        {
            "name": "Mike",
            "incentives": "23.45",
            "id": "1"
        },
        {
            "name": "Larsen",
            "incentives": "34.78",
            "id": "2"
        },
        {
            "name": "Steve",
            "incentives": "26.78",
            "id": "3"
        }
    ];
    
    var filtered = test.filter(function(object) {
    
        return object.id != 2;
    });
    
    console.log(filtered);

答案 3 :(得分:0)

如果要删除多个ID,这是使用reduce的另一种方法。这与其他方法和答案没有太大不同,但是完成提问的方式不同。

var test = [{
    "name": "Mike",
    "incentives": "23.45",
    "id": "1"
  },
  {
    "name": "Larsen",
    "incentives": "34.78",
    "id": "2"
  },
  {
    "name": "Steve",
    "incentives": "26.78",
    "id": "3"
  }
];

function removeItem(idList) {

  var result = test.reduce(function(output, currentObject) {
    if (!idList.includes(currentObject.id)) {
      output.push(currentObject);
    }
    return output;
  }, []);
  return result;
}


console.log(removeItem(["2", '3']))