问题描述
我正在使用函数组件在 React js 中工作。我需要删除与索引对应的数组对象,并将新的数组对象添加到相同的索引。下面给出了多维数组对象的示例。我尝试了一些方法,但没有给我正确的答案。我认为问题很明显。如果有任何疑问,请务必询问。
原始数组对象
[
{
"area": "Zone1","cartamount": "","extra_shippingamount": "","polygon": [
[
{
"lat": 11.174036305817275,"lng": 76.3754534171875
},{
"lat": 10.526644973776667,"lng": 76.6061663078125
},{
"lat": 10.75339097376777,"lng": 77.47957939375
}
],[
{
"lat": 11.28179683077826,"lng": 75.89857811201172
},{
"lat": 10.774977003245414,"lng": 76.16774315107422
},{
"lat": 11.292570666429365,"lng": 76.91481346357422
}
]
],"shippingamount": ""
},{
"area": "Zone2","lng": 77.47957939375
}
]
],{
"area": "Zone3","polygon": [
[
{
"lat": 10.755303390976334,"lng": 76.4073785765625
},{
"lat": 10.182723497824039,"lng": 76.4018854125
},{
"lat": 10.150282003909208,"lng": 77.3082574828125
},{
"lat": 10.74990667635129,"lng": 77.291777990625
},{
"lat": 11.062755098084468,"lng": 77.0445856078125
}
]
],"shippingamount": ""
}
]
已编辑的对象数组
[{
"area": "Zone1","polygon": [
[{
"lat": 11.174036305817275,[{
"lat": 9.62536187827369,"lng": 76.88150729970702
},{
"lat": 9.023680418742487,"lng": 76.77164401845702
},{
"lat": 9.299749165335365,"lng": 78.76737918691406
}
]
],"polygon": [
[{
"lat": 10.755303390976334,"shippingamount": ""
}
]
const onEdit = useCallback(() => {
if (polygonRef.current) {
const nextPath = polygonRef?.current
.getPath()
.getArray()
.map((latLng: any) => {
return { lat: latLng.lat(),lng: latLng.lng() };
});
setPath(nextPath);
// const nextPath=[{
// "lat": 9.62536187827369,// "lng": 76.88150729970702
// },// {
// "lat": 9.023680418742487,// "lng": 76.77164401845702
// },// {
// "lat": 9.299749165335365,// "lng": 78.76737918691406
// }]
let getMapzones = localStorage.getItem("mapZone");
if (typeof getMapzones == 'string') {
let localZone = JSON.parse(getMapzones);
let tempData = localZone?.map((item: any,key: any) => {
if (key == coordindex) {
return item?.polygon?.map((el: any,index: any) => {
if (index == curIndex) {
el = nextPath
return el
}
else {
return el
}
})
}
else {
return item
}
})
localStorage.setItem('mapZone',JSON.stringify(tempData))
}
}
},[coordindex,curIndex])
我的代码输出 丢失了与索引对应的数组中的其他值(area、cartamount、extra_shippingamount、shippingamount)和其他多边形值。新数组对象替换整个数组。
[
[
[{
"lat": 9.62536187827369,"lng": 76.88150729970702
},{
"lat": 9.023680418742487,"lng": 76.77164401845702
},{
"lat": 9.299749165335365,"lng": 78.76737918691406
}
]
],"shippingamount": ""
}
]
解决方法
为什么不尝试拼接数组呢?在这种情况下不需要映射数组,因为 splice 将适用于您的原始数组。如果你不愿意修改你原来的数组,你可以把它存储在一个临时数组中,然后操作这个临时数组。
arr.splice(indexToBeManipulated,1,newValue);
.splice() 将第一个参数作为您想要开始更改的索引,第二个参数如果作为 0 传递将不会删除从 indexToBeManipulaed 开始的任何元素。但在您的情况下,由于您想从相应的索引中删除一个值,因此第二个参数应该是 1,第三个参数可以是您想要附加到 indexToBeManipulaed 的新值。
查看此链接以更好地理解 .splice() :https://www.w3schools.com/jsref/jsref_splice.asp