正在同步运行.filter和.map



你好,我在运行此函数时遇到问题,我试图过滤一个对象数组,然后通过用.map的索引重新分配我的id进行重组。出现的问题是.filter没有删除/删除函数中的项。以下是我的代码作为参考:什么是最好的解决方案。任何意见都会很有帮助,谢谢。

const removeData = (id) => {
const del = idleData.filter(idle => id !== idle.id).map((item,index) => (
{
id: index, 
days: item.day,
comments: item.comments,
cost: item.cost,
reason: item.reason,
portCallVoyageId: item.portCallVoyageId,
changedBy: item.changedBy
}
));
setIdleData(del);
}

这里是idleData和idle:

idleData = [{
id: 0,
cost: 10,
days: 10,
comments: 'comment 1',
reason: "reason 1",
changedBy: "user1"
}, {
id: 1,
cost: 20,
days: 20,
comments: 'comment 2',
reason: "reason 2",
changedBy: "user2"
}];
idle = 0;

刚刚测试了您的代码,我认为它运行良好,可能的问题在idle变量中。

我稍微重写了源代码。

const idleData = [
{id: 0,cost: 10,days: 10,comments: 'comment 1',reason: "reason 1",changedBy: "user1"}, 
{id: 1,cost: 20,days: 20,comments: 'comment 2',reason: "reason 2",changedBy: "user2"},
{id: 2,cost: 30,days: 30,comments: 'comment 3',reason: "reason 3",changedBy: "user3"},
{id: 3,cost: 40,days: 40,comments: 'comment 4',reason: "reason 4",changedBy: "user4"},
{id: 4,cost: 50,days: 50,comments: 'comment 5',reason: "reason 5",changedBy: "user5"},
];
//idle = 0; 
const removeData = (omitId) => {
const del = idleData
.filter(({ id }) => id !== omitId)
.map((item, index) => ({ ...item, id: index }));
console.log(del);
// setIdleData(del);
};
console.log(del);
// setIdleData(del);
};
removeData(0);
.as-console-wrapper{min-height: 100%!important; top: 0}

相同的结果,但没有.filter

const idleData = [
{id: 0,cost: 10,days: 10,comments: 'comment 1',reason: "reason 1",changedBy: "user1"}, 
{id: 1,cost: 20,days: 20,comments: 'comment 2',reason: "reason 2",changedBy: "user2"},
{id: 2,cost: 30,days: 30,comments: 'comment 3',reason: "reason 3",changedBy: "user3"},
{id: 3,cost: 40,days: 40,comments: 'comment 4',reason: "reason 4",changedBy: "user4"},
{id: 4,cost: 50,days: 50,comments: 'comment 5',reason: "reason 5",changedBy: "user5"},
];
//idle = 0; 
const removeData = (omitId) => {
const del = idleData
.flatMap((item, index) => (item.id !== omitId) 
? { ...item, id: index } 
: []);
console.log(del);
// setIdleData(del);
};

removeData(0);
.as-console-wrapper{min-height: 100%!important; top: 0}

您的代码正在像冠军一样工作!我正在添加下面的代码片段。请告诉我您面临的挑战。我将根据输入对其进行修改。

演示:

const idleData = [{
id: 0,
cost: 10,
days: 10,
comments: 'comment 1',
reason: "reason 1",
changedBy: "user1"
}, {
id: 1,
cost: 20,
days: 20,
comments: 'comment 2',
reason: "reason 2",
changedBy: "user2"
}];
const removeData = (id) => {
const del = idleData.filter(idle => id !== idle.id).map((item,index) => (
{
id: index, 
days: item.day,
comments: item.comments,
cost: item.cost,
reason: item.reason,
portCallVoyageId: item.portCallVoyageId,
changedBy: item.changedBy
}
));
console.log(del);
}

removeData(0);

最新更新