简体   繁体   English

如何克隆 JavaScript object?

[英]How do I clone a JavaScript object?

In the function formatHours() below, I am trying to assign newHours to selectedLocation.data.hours (an object)在下面的 function formatHours()中,我试图将newHours分配给selectedLocation.data.hours (一个对象)

I am using the spread operator to clone the object, so that when the function finishes selectedLocation.data.hours remains the same, but it doesn't.我正在使用扩展运算符克隆 object,这样当 function 完成时selectedLocation.data.hours保持不变,但事实并非如此。 After this function runs, selectedLocationd.data.hours is now equal to newHours .在 function 运行之后, 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);
  };  

Here's what selectedLocation.data.hours looks like BEFORE passing it through formatHours() :这是selectedLocation.data.hours在通过formatHours()之前的样子:

(object of arrays of Firebase Firestore timestamps) (Firebase Firestore 时间戳的 arrays 对象)

在此处输入图像描述

Here's what selectedLocation.data.hours looks like AFTER passing it through formatHours() :这是selectedLocation.data.hours通过formatHours()后的样子:

(object of arrays of Javascript Date objects) (Javascript 日期对象的 arrays 对象)

在此处输入图像描述

NOTE: selectedLocation.data.hours should stay the same before and after the function, but doesn't.注意: selectedLocation.data.hours在 function 之前和之后应该保持不变,但不会。 I must be missing something.我肯定错过了什么。

Instead of changing the newHours[hour] array (which mutates the object currently in state/props), create an entirely new array at that location, with the properties you need:不要更改newHours[hour]数组(它会改变当前状态/道具中的 object),而是在该位置创建一个全新的数组,其中包含您需要的属性:

// 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]
  ];
}

Another method, with Object.fromEntries :另一种方法,使用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]
            ]
        ]
    ))
);

I'm not sure if it's the best way to do that, but you can do this我不确定这是否是最好的方法,但你可以这样做

 const newHours = JSON.parse(JSON.stringify(selectedLocation.data.hours));

This will deep clone the object.这将深度克隆 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM