使用.filter方法从数组中删除一个元素的Node.Js方法

3

我有一个对象数组,我想根据用户传入的参数来删除特定的项,

removeItem = (title, body){

let myArray = [
  { title : 'title 1', body: 'body of title one' },
  { title : 'title 2', body: 'body of title two' },
  { title : 'title 3', body: 'body of title three' },
]

//the problem is down here
let filteredArray = myArray.filter(item => {
  item.title != title || item.body != body
}
  
// at this point i assume that the filtered array will not
// include the item that i want to remove
// so down here i reset the value of my original array to the filtered one
 
myArray = filteredArray

简单来说,我想要运行的测试是,如果用户的标题或正文与数组中的任何一个标题或正文都不匹配,则将此项放入新的数组中,从而得到一个筛选好的数组。。
但是,以上代码会删除所有内容并返回一个空数组.. 有人能帮忙纠正上述逻辑吗?谢谢。

1
过滤函数需要返回一个布尔值,如果你想“保留”它则为true,否则为false以删除它。因此,你的代码应该是return item.title != title || item.body != body - DPac
代码无法运行。 - brk
4个回答

3

要么在箭头函数中添加return语句,要么删除花括号:)

myArray = myArray.filter(item => {
  return item.title != title || item.body != body;
});

或者

myArray = myArray.filter(item => item.title != title || item.body != body);

2

来自 MDN Filter 页面

回调函数 是一个谓词函数,用于测试数组的每个元素。如果返回值为 true,则保留该元素;否则,舍弃该元素。它接受三个参数:

你的回调函数没有任何 return 关键字。默认情况下,JS 将其解释为 undefined,即非真值/假值。因此,所有的项都不符合过滤条件,最终得到一个空数组。

此外,正如其他人指出的,你缺少了一个括号。

let filteredArray = myArray.filter(item => {
    return item.title != title || item.body != body;
});

哇 :D,我真的很惊讶你们所有人的反应非常迅速 :) 非常感谢你们的回答确实解决了问题,非常感激 ;) 干杯 - Swilam Muhammad

2
你需要在过滤器函数中返回一个布尔值。如果要保留元素,请返回true;否则,返回false。 目前你返回的是未定义的undefined,即为false。

let myArray = [
  {title : 'title 1', body: 'body of title one'},
  {title : 'title 2', body: 'body of title two'},
  {title : 'title 3', body: 'body of title three'}
]
let title = "title 1";
let body = "body of title one";


let filteredArray = myArray.filter((item) =>item.title != title || item.body != body);

 console.log(filteredArray);

For reference : Array.filter()


0

如果您想要过滤出标题或正文中任意一个不匹配的情况,您需要在布尔值中使用&&

例如,如果您的title是"title 1",而您的body是"body of title two",那么它应该返回的唯一项目是title 3,因为这是唯一一个既不匹配标题也不匹配正文的项目。

当然,您需要从您的过滤器回调函数中返回此结果,因此请删除函数体周围的{}或明确返回该值。

const removeItem = (title, body) => {
  let myArray = [
    {title : 'title 1', body: 'body of title one'},
    {title : 'title 2', body: 'body of title two'},
    {title : 'title 3', body: 'body of title three'}
  ]
  
  let filteredArray = myArray.filter((item) =>
    item.title != title 
    && item.body != body
  );
  return filteredArray  
}

 console.log(removeItem( // should only return title 3
  "title 1",
  "body of title two"
 ));

 console.log(removeItem( //should return title 2 and title 3
  "title 1",
  "body of title one"
 ));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接