簡體   English   中英

Lodash相當於JSON.parse(JSON.stringify())

[英]Lodash equivalent of JSON.parse(JSON.stringify())

我目前正在克隆一個對象:

var copy = JSON.parse(JSON.stringify(original));

當我嘗試lodash時 - 似乎推薦的方法是cloneDeep(),但這對我來說總是一團糟。 我的對象部分由Mongoose查詢的結果組成,這可能是造成這種情況的原因。

原版的:

template: 'email/receipt.swig',
templateVars: { 
  code: '299137819',

用lodash克隆:

template: 'email/receipt.swig',
templateVars: { 
  '$__': { 
    strictMode: true,
    selected: undefined,
    shardval: undefined,
    saveError: undefined,
    validationError: undefined,
    adhocPaths: undefined,
    removing: undefined,
    inserting: true,
    version: undefined,
    getters: [Object],
    _id: undefined,
    populate: undefined,
    populated: [Object],
    wasPopulated: false,
    scope: [Circular],
    activePaths: [Object],
    ownerDocument: undefined,
    fullPath: undefined 
  },
  isNew: false,
  errors: undefined,
  _maxListeners: 0,
  _events: { save: [Object], isNew: [Object] },
  _doc: { 
    code: '299137819'

這里發生了什么? 這顯然是Mongo的東西,但為什么重新格式化? 有沒有辦法用lodash制作精確的副本? 並不是說我當前的方法很痛苦 - 只是試圖理解為什么人們說cloneDeep是等價的。

從Mongoose返回的對象不是像你可能期望從數據庫中獲得的原始鍵值,但它們還有許多其他功能。最終, cloneDeep執行此操作 ,最終復制包括函數和其他您可能不需要的內容的所有內容。

JSON.stringify以及.toJSON將工作因為toJSON行為。

所以實際上它們並不等同,因為你可以重新定義JSON序列化行為,而JSON 絕不會序列化函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM