如何克隆JavaScript对象?

devon66h

formatHours()下面的函数中,我尝试分配newHoursselectedLocation.data.hours(一个对象)

我正在使用传播运算符来克隆对象,以便函数完成时selectedLocation.data.hours保持不变,但事实并非如此。该函数运行后,selectedLocationd.data.hours现在等于newHours

formatHours():

const formatHours = () => {
    // ERROR: trying to clone selectedLocation.data.hours, but not working
    const newHours = { ...selectedLocation.data.hours };

    // loop through all hours and convert them to javascript date with .toDate()
    for (const hour in newHours) {
      newHours[hour][0] = newHours[hour][0].toDate();
      newHours[hour][1] = newHours[hour][1].toDate();
    }

    // set hours state with updated hours
    setHours(newHours);
  };  

selectedLocation.data.hours看起来像是在传递之前formatHours()

(Firebase Firestore时间戳记数组的对象)

在此处输入图片说明

这是selectedLocation.data.hours经过它之后样子formatHours()

(JavaScript Date对象数组的对象)

在此处输入图片说明

注意: selectedLocation.data.hours该功能前后应保持不变,但不是。我肯定错过了什么。

一定的表现

无需更改newHours[hour]数组(该数组会使当前处于状态/属性的对象发生变化),而无需在该位置使用所需的属性创建一个全新的数组

// Shallow clone newHours
const newHours = { ...selectedLocation.data.hours };
// Reassign each property; it'll affect the clone, not the original
for (const [hour, arr] of Object.entries(newHours)) {
  newHours[hour] = [
    arr[0].toDate(),
    arr[1].toDate(),
    arr[2]
  ];
}

另一种方法是Object.fromEntries

const newHours = Object.fromEntries(
    Object.entries(selectedLocation.data.hours).map(([hour, arr]) => (
        [ // return an entry array
            hour, // key in new object
            [ // value in new object
                arr[0].toDate(),
                arr[1].toDate(),
                arr[2]
            ]
        ]
    ))
);

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章