ii iml0sto1
ii iml0sto1

Reputation: 1742

Javascript remove object from array if object contains string

I have an array of objects looking similar to this

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

Lets assume i have this string Car how do i search through the array of objects to find which object if any contains that particular string in the name key and then remove that object from the array of objects?

This is what i got so far (Basically nothing because i dont know what to do from here)

function remove_obj_from_array_of_objs(str, array_of_objs){

}

Upvotes: 3

Views: 8668

Answers (4)

Mamun
Mamun

Reputation: 68933

Try Array's filter() like the following:

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);

Upvotes: 3

Léo R.
Léo R.

Reputation: 2708

First you loop over your array and compare Key value with your Search String, if equals, you remove object with his index from array :

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);
        }
    }
}

Upvotes: 0

void
void

Reputation: 36703

Use Array.filter to filter the result of array based on some condition.

_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);

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can use filter() and includes() methods for this.

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)

Upvotes: 11

Related Questions