首页 > 解决方案 > 深拷贝 json 简化

问题描述

试图复制一个 json 对象,但是当其中有一个字符串时,我只需要其中的几个键/值对并将其复制到另一个 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 中的字符串中获取特定值。尝试过深拷贝,但无法正确完成。这并不是说我没有尝试过完成这项工作,而是无法想出一种方法让它更通用而不是硬编码。任何帮助,将不胜感激。

标签: arraysjsonnode.jsdeep-copy

解决方案


既然你说它只会是一个级别的深度,那么你真的不需要一个“深度”副本可以这么说。听起来好像您只需要测试字符串以查看它们是否JSON.parse可以,如果可以,则将它们的键/值对包含在对象中。

如果是这种情况,一个简单的 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);


推荐阅读