gpt4 book ai didi

javascript - 对象内部的数组未正确删除

转载 作者:行者123 更新时间:2023-12-02 21:05:31 25 4
gpt4 key购买 nike

我有一个名为位置的数组

const [location,setLocation]=useState([]);


const addLocation=(place)=>{ // place={name:"abc",pin:"232",person:[]}
const _location=[...location];
const person1={name:"dfg",age:"10"}
place.person.push(person1);
setlocation([...location,place]);
}

const removeLocation=(index)=>{
const _location=[...location];
_location.splice(index,1)
setLocation(_location);
}

状态变为空

但问题是,如果我再次添加同一个人,则人员数组会再次使用同一对象增加像这样

{name:"abc",pin:"232",person:[{name:"dfg",age:"10"},{name:"dfg",age:"10"}]} 

最佳答案

在将该人添加到该位置之前,您必须检查他可能已经存在的任何内容。
你可以像这样轻松地做到这一点:

const addLocation = (place) => {
const _location=[...location];
const person1={name:"dfg",age:"10"};
if(place.person.findIndex(e => e.name === person1.name) === -1)
place.person.push(person1);
setlocation([...location,place]);
}

在我的示例中,我仅检查人名。您也可以添加其他内容。

关于javascript - 对象内部的数组未正确删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61235747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com