javascript - Node.JS - filter() 仅在对索引进行硬编码时才有效
问题描述
尝试过滤和排列以获取与用户输入不匹配的对象。删除一本书。
用户输入:
{
title: 'WindFall',
author: 'Jaime',
body: 'another body of a body'
}
过滤器正在查看的数组(来自 JSON 然后解析):
[
{ title: 'title1', author: 'samson', body: 'this is the body' },
{
title: 'WindFall',
author: 'Jaime',
body: 'another body of a body'
}
]
代码库:
function removeItem(item) {
try {
const arrOfBooks = fs.readFileSync("./appendJSON.json").toString();
const arrOfBooksParse = JSON.parse(arrOfBooks);
const newArr = arrOfBooksParse.filter(item => {
return arrOfBooksParse[item].title !== item.title;
});
console.log(newArr);
} catch (error) {
console.log("There is nothing to remove");
}
}
因为我知道===
用户输入的第二个对象,硬编码,
return arrOfBooksParse[1].title !== item.title;
工作,但return arrOfBooksParse[item].title !== item.title;
没有。取而代之的是catch
intry/catch
熄灭。
解决方案
item 它是数组中的对象。它没有索引。并且“item”从参数中覆盖“item”
固定代码:
function removeItem(item) {
try {
const arrOfBooks = fs.readFileSync("./appendJSON.json").toString();
const arrOfBooksParse = JSON.parse(arrOfBooks);
const newArr = arrOfBooksParse.filter((i) => i.title !== item.title);
console.log(newArr);
} catch (error) {
console.log("There is nothing to remove");
}
}
推荐阅读
- laravel - 我的 Laravel 引导方法不接受任何条件
- python - 如何将函数属性用作python对象以及字符串
- javascript - 使用 cryptico 库进行解密的 Javascript 错误
- rxjs - 如何保持多窗口Angular App之间的通信
- mongodb-stitch - 为什么我的 mongodb-stitch 服务返回值类型($numberLong, $numberInt,...)?
- php - PHP PDO 语句 - 作为 pdo->query 工作,而不是作为 pdo->prepare 工作
- android - 如何使用上传证书发布应用更新?
- r - 填补数据框中日期之间的空白
- php - 使用正则表达式替换重复模式
- sql - 让 LOCATE 返回变量 SQL DB2