繁体   English   中英

没有引用的深度复制 Node JS 对象

[英]Deep copy Node JS object without reference

我有 4 级对象结构,我需要将其放在缓存中。 一旦从缓存中检索到数据,就需要在发送响应之前对其进行操作。

为此,我如何在没有参考的情况下进行深拷贝。

我尝试了 _.clone 和 Object.assign。 他们都没有工作

dbCharges (24) [模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型、模型, 模型]

每个模型都有内部对象

模型数据值:{Service_Provider_Location_Charge_Id: 2084, Sequence: 2, Visible_On_Screen: true, Possible_Values: "Commercial;COM,Private;PRI,UK Military;MIL,Non UK Military;NMIL", Default_Value: null, …} isNewRecord: true eagerlyLoadedAssociations: [] _changed: {Service_Provider_Location_Charge_Id: true, Sequence: true, Visible_On_Screen: true, Possible_Values: true, Default_Value: true, …} _modelOptions: {timestamps: true, validate: {…}, freezeTableName: false, underscored: true, underscoredAll:真,...} _options: {isNewRecord: true, _schema: null, _schemaDelimiter: ""} _previousDataValues: {Service_Provider_Location_Charge_Id: undefined, Sequence: undefined, Visible_On_Screen: undefined, Possible_Values: undefined, Default_Value: undefined, ...} Charge: Object ChargeType:模型数据值:{Charge_Type_Id:2,描述:“Checkbox”,Is_Active:true,Created_On:2016 年 4 月 1 日星期五 07:35:00 GMT+0100(英国夏令时),Created_By:“SYSTEM”,...} isNewRecord:true __eagerlyLoadedAssoci ations: [] _changed: {Charge_Type_Id: true, Description: true, Is_Active: true, Created_On: true, Created_By: true, …} _modelOptions: {timestamps: true, validate: {…}, freezeTableName: false, underscored: true, underscoredAll: true, …} _options: {isNewRecord: true, _schema: null, _schemaDelimiter: ""} _previousDataValues: {Charge_Type_Id: undefined, Description: undefined, Is_Active: undefined, Created_On: undefined, Created_By: undefined, ...} After_Decimals: ( ...) Charge_Type_Id: (...) Created_By: (...) Created_On: (...) Datatype: (...) Description: (...) Is_Active: (...) Modified_By: (. ..) Modified_On: (...) Total_Length: (...) TypeDescription: (...) sequelize: (...) __proto : Model Charge_Id: 2 Charge_Type_Id: (...) Created_By: (... ) Created_On: (...) Default_Value: (...) Default_Value_Rule_Id: (...) Default_Value_Rules: (...) Formula_Description: (...) Formula_Is_Active: (...) Formula_Name: (...) Formula_Notes: (...) Help_Text: (...) Invoice_Description: (...) Is_Active: (...) Is_Ed itable: (...) Is_Editable_Rules: (...) Is_Visible_On_Delivery_Ticket: (...) Local_Description: (...) Modified_By: (...) Modified_On: (...) Name_On_Delivery_Ticket: (...) Possible_Values :(...)序列:(...)Service_Provider_Location_Charge_Id:(...)Visible_On_Screen:(...)Visible_On_Screen_Rule_Id:(...)Visible_On_Screen_Rules:(...)

_.clone仅创建对象的浅克隆。
尝试_.cloneDeep

您尝试的方法允许制作浅拷贝,而不是深拷贝。 请参阅此问题以了解 deep copy 和 shallow copy 之间的区别

要制作深拷贝,您可以使用_.cloneDeep中的 _.cloneDeep。

const data = [{ 'a': 1 }, { 'b': 2 }];

const deepCopy = _.cloneDeep(data);

你也可以在没有任何库的情况下进行深拷贝:

const deepCopy = JSON.parse(JSON.stringify(data));

暂无
暂无

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

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