如果对象包含字符串,则Javascript从数组中删除对象

时间:2018-02-13 15:38:58

标签: javascript arrays object

我有一个类似于此

的对象数组
[{ id: "11", name: "Car", symbol: "CA" }
,{ id: "13", name: "Cycle", symbol: "CY" }
,{ id: "15", name: "Train", symbol: "TA" }
,{ id: "3", name: "Ufo", symbol: "UF" }]

让我们假设我有这个字符串Car如何搜索对象数组以查找哪个对象(如果有的话)在name键中包含该特定字符串然后从对象数组中删除该对象?

这是我到目前为止所得到的(基本上没什么,因为我不知道该怎么做)

function remove_obj_from_array_of_objs(str, array_of_objs){

}

4 个答案:

答案 0 :(得分:3)

您可以使用filter()includes()方法。

const data = [{ id: "11", name: "Car", symbol: "CA" },{ id: "13", name: "Cycle", symbol: "CY" },{ id: "15", name: "Train", symbol: "TA" },{ id: "3", name: "Ufo", symbol: "UF" }]

const result = data.filter(({name}) => !name.includes('Car'))
console.log(result)

答案 1 :(得分:1)

使用Array.filter根据某些条件过滤数组的结果。

_arr.filter( el => el.name!==_str);

var data = [{ id: "11", name: "Car", symbol: "CA" }
,{ id: "13", name: "Cycle", symbol: "CY" }
,{ id: "15", name: "Train", symbol: "TA" }
,{ id: "3", name: "Ufo", symbol: "UF" }]

function remove_item_array_of_objs(_str, _arr){
  return  _arr.filter( el => el.name!==_str);
}

var resp = remove_item_array_of_objs("Car", data);
console.log(resp);

答案 2 :(得分:0)

尝试数组filter(),如下所示:

var carArr = [{ id: "11", name: "Car", symbol: "CA" }
,{ id: "13", name: "Cycle", symbol: "CY" }
,{ id: "15", name: "Train", symbol: "TA" }
,{ id: "3", name: "Ufo", symbol: "UF" }];

var notIncludesCar = carArr.filter(item => !item.name.includes("Car"));

console.log(notIncludesCar);

答案 3 :(得分:0)

首先循环遍历数组并将Key值与Search String进行比较,如果等于,则从数组中删除带有索引的对象:

function remove_item_array_of_objs(string, array_of_objs){
    for (var i=0; i < array_of_objs.length; i++) {
        if (array_of_objs[i].name === string) {
            array_of_objs.splice(i, 1);
        }
    }
}