簡體   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