Search code examples
arraysjsonnode.jsdeep-copy

deep copy json simplied


Trying to copy a json object but when there is a string in it I need only few key/value pairs from it and have it copied to another json object (simplified); Data in JSON is something like this

{ __createdAt: "2018-07-30T08:19:32.523Z",
  orderid: '12345',
  refund: null,
  order_verified: null,
  in_process: null,
  location_id: null,
  userInfo: '{"countrySelect":"DE","postalCode":"64289","ShippingCountry":"Germany","City":"Darmstadt","GooglePlace":"Darmstadt Germany","ShippingRegion":"Hesse","CustomerEmail":"[email protected]"}',
  payment: null,
  shippingInfo: 1437,
  taxInfo: 0,
  orderTotal: 5712,
  order_weight: 0,
  order_notes: '' }

The result I am trying to achieve after copying is something like this.

{ __createdAt: "2018-07-30T08:19:32.523Z",
  orderid: '12345',
  refund: null,
  order_verified: null,
  in_process: null,
  location_id: null,
  countrySelect:"DE",
  ShippingCountry:"Germany",
  City:"Darmstadt",
  CustomerEmail:"[email protected]",
  payment: null,
  shippingInfo: 1437,
  taxInfo: 0,
  orderTotal: 5712,
  order_weight: 0,
  order_notes: '' }

I dont know what data would come from the DB, but whenever it contains string I could hardcode it to get specific values from string within a json. Tried deep copy, but couldn't get this done correctly. Its not that I haven't tried getting this done but couldn't come up a way to make it more generic instead of hardcoded. Any help would be appreciated.


Solution

  • Since you say it will only ever be one level deep, you don't really need a "deep" copy so to speak. It sounds as if you only need to test strings to see if they are JSON.parseable, and if so to include their key/value pairs in the object.

    If that's the case, a simple try/catch will do the trick. You could also add another check after the JSON.parse to verify that the output of the parse is in fact an object, or to filter out certain key values, etc.

    const src = {
      __createdAt: "2018-07-30T08:19:32.523Z", orderid: '12345', refund: null, order_verified: null, in_process: null, location_id: null,
      userInfo: '{"countrySelect":"DE","postalCode":"64289","ShippingCountry":"Germany","City":"Darmstadt","GooglePlace":"Darmstadt Germany","ShippingRegion":"Hesse","CustomerEmail":"[email protected]"}',
      payment: null, shippingInfo: 1437, taxInfo: 0, orderTotal: 5712, order_weight: 0, order_notes: ''
    }
    
    function copyExpand(target, source) {
      for (let k in source) {
        if (typeof source[k] === 'string') {
          try {
            let json = JSON.parse(source[k]);
            copyExpand(target, json);
          } catch (e) {
            target[k] = source[k];
          }
        } else target[k] = source[k];
      }
    }
    const tgt = {};
    copyExpand(tgt, src);
    console.log(tgt);