【问题标题】:deep copy json simplied深拷贝json简化
【发布时间】:2018-08-26 22:05:03
【问题描述】:

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

【问题讨论】:

  • 您需要提供更多上下文,JSON 字符串是不是我曾经的 1 级深度?
  • 是的。可能有多个 JSON 字符串,但只有一层。
  • 是否总是 userInfo 属性包含 JSON?
  • 不,但不超过 2 或 3 个。这是必须很少硬编码的部分。
  • 如果出现“userInfo”,我们会从中复制 2 3 个预定义的键/值。

标签: arrays json node.js deep-copy


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多