Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 602
ii iml0sto1 Avatar asked Aug 15 '26 15:08

ii iml0sto1


2 Answers

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)
like image 111
Nenad Vracar Avatar answered Aug 17 '26 05:08

Nenad Vracar


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);
like image 29
Mamun Avatar answered Aug 17 '26 04:08

Mamun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!