深层复制 json 简化

deep copy json simplied

试图复制一个 json 对象,但当其中有一个字符串时,我只需要从中提取几对 key/value 并将其复制到另一个 json 对象(已简化) ; JSON 中的数据是这样的

{ __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":"myemail@gmail.com"}',
  payment: null,
  shippingInfo: 1437,
  taxInfo: 0,
  orderTotal: 5712,
  order_weight: 0,
  order_notes: '' }

我复制后想要达到的效果是这样的。

{ __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:"myemail@gmail.com",
  payment: null,
  shippingInfo: 1437,
  taxInfo: 0,
  orderTotal: 5712,
  order_weight: 0,
  order_notes: '' }

我不知道什么数据会来自数据库,但只要它包含字符串,我就可以对其进行硬编码以从 json 中的字符串中获取特定值。 尝试了深拷贝,但无法正确完成。这并不是说我没有尝试完成这项工作,而是想不出一种方法让它更通用而不是硬编码。任何帮助,将不胜感激。

既然你说它永远只有一层深,那么可以这么说,你真的不需要 "deep" 副本。听起来好像您只需要测试字符串以查看它们是否 JSON.parseable,如果可以,则将它们的 key/value 对包含在对象中。

如果是这种情况,一个简单的 try/catch 就可以解决问题。您还可以在 JSON.parse 之后添加另一个检查,以验证解析的输出实际上是一个对象,或者过滤掉某些键值等。

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":"myemail@gmail.com"}',
  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);