Arun Karthick
Arun Karthick

Reputation: 336

Remove all objects from json data which contains a specific keyword

I'm just looking for the best practice to remove remove all objects from json data which contains a specific term/keyword.

my json data looks like this

json = [{
 "name":"John",
 "age":30,
 "cars":"BMW"
},
{
 "name":"Micheal",
 "age":30,
 "cars":"Ford,BMW"
},
{
 "name":"Andy",
 "age":29,
 "cars":"Ford"
},
{
 "name":"Andy",
 "age":29,
 "cars":"Ford,Toyota"
}];

I want to remove the objects which has the keyword "BMW".

Upvotes: 2

Views: 547

Answers (2)

Haritsinh Gohil
Haritsinh Gohil

Reputation: 6272

For removing element from array of objects based containing string Array.filter is best solution but its another alternative can be Array.reduce as below:

var arr =[{ "name":"John", "age":30, "cars":"BMW" }, { "name":"Micheal", "age":30, "cars":"Ford,BMW" }, { "name":"Andy", "age":29, "cars":"Ford" }, { "name":"Andy", "age":29, "cars":"Ford,Toyota" }];

var newarr = arr.reduce((acc, elem) => !elem.cars.includes("BMW") ? acc.concat(elem) : acc, []);

console.log(newarr);

Upvotes: 0

amrender singh
amrender singh

Reputation: 8239

You can simply use Array.filter():

var arr = [{ "name":"John", "age":30, "cars":"BMW" }, { "name":"Micheal", "age":30, "cars":"Ford,BMW" }, { "name":"Andy", "age":29, "cars":"Ford" }, { "name":"Andy", "age":29, "cars":"Ford,Toyota" }];

var result = arr.filter(({cars})=> !cars.includes("BMW"));

console.log(result);

Upvotes: 4

Related Questions