我只是在寻找最佳实践,以删除从包含特定术语/关键字的json数据中删除所有对象的方法。
我的json数据看起来像这样
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"
}];
我要删除关键字为“ BMW”的对象。
答案 0 :(得分:4)
您可以简单地使用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);
答案 1 :(得分:0)
对于从包含字符串的对象数组中删除元素,Array.filter
是最佳解决方案,但其另一个替代可以是Array.reduce
,如下所示:< / p>
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);