防止原始数组被更改

表面新

我有一个包含一些 geoJSON 数据的数组。我想创建一个新数组,该数组由属性部分中的另一个键组成的数据组成。但它不断改变原始数组。如何防止它更改原始数组?

const [citys, setCitys] = useState(someGeoJson)
const [manipulatedArray, setManipulatedArray] = useState([])

function createManiArray() {
  let currentManipulatedArray = []
  citys.features.forEach((city) => {
    let currentCity = city
    currentCity.properties = { ...city.properties,
      value: Math.random()
    }
    currentManipulatedArray .push(currentCity)
    //My problem now is that this changes the orginal city array, how can i prevent that from happening?

  })
  setManipulatedArray(currentManipulatedArray)
}
安迪
  1. 你没有setManipulatedArray用来设置状态。

  2. 您应该使用map创建一个新的对象数组而不是改变原始数组。

const [cities, setCities] = useState(someGeoJson);

const [manipulatedArray, setManipulatedArray] = useState([]);

function createManiArray() {

  // Create a new array of objects with an updated
  // properties object
  const updated = cities.features.map(city => {
    return {
      ...city,
      properties: {
        ...city.properties,
        value: Math.random()
      }
    };
  });
  
  // Set the new state with that array
  setManipulatedArray(updated);

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何防止扩展运算符更改原始数组?

打印原始数组和更改的数组

当参考更改时,如何防止更改原始对象?

原始数组更改,未做任何修改

PHP foreach更改原始数组值

.sort函数会更改原始数组吗?

为什么我的原始数组被更改?

过滤javascript树而不更改原始数组

为什么更改副本时原始数组会更改?

如何复制json数组而不更改原始数组值

Javascript中的反向数组而不更改原始数组

如何基于其他数组更改原始数组

修改数组内的对象属性而不更改原始数组

如何复制数组并使用副本而不更改原始数组?

当模板与原始数组绑定时,是否在不更改原始数组的情况下搜索功能?

PHP foreach更改二维原始数组值

使用array.clone()并更改值也会影响原始数组

可以更改数组中的原始变量吗?

为什么修改array.slice()也会更改原始数组?

PHP-嵌套的Foreach更改原始数组值

JS从数组中删除元素而不更改原始元素

如何使用过滤器更改原始数组?

在引用变量中更改时原始数组未更新

Keil IDE自动更改我的char数组原始值

Python:应用掩码而不更改原始数组的值

更改二维数组变量也会更改原始二维数组变量。为什么?

如何更改数组的克隆而不更改reactjs中的原始数组

如何防止在类对象中引用原始熊猫数据框时更改其值?

使用ng-repeat in angle防止更改“复制”对象而影响原始对象