首页
学习
活动
专区
圈层
工具
发布

深拷贝
EN

Stack Overflow用户
提问于 2018-08-26 22:05:03
回答 1查看 45关注 0票数 0

尝试复制一个json对象,但是当其中有一个字符串时,我只需要从它中复制几个键/值对,并将它复制到另一个json对象(简化);JSON中的数据类似于

代码语言:javascript
复制
{ __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: '' }

在复制之后,我试图达到的结果是这样的。

代码语言:javascript
复制
{ __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: '' }

我不知道什么数据将来自DB,但是每当它包含字符串时,我都可以硬编码它,以便从json中的字符串中获取特定的值。试过深拷贝,但做不到。这并不是说我还没有尝试完成这个任务,但我无法想出一种方法来使它变得更通用,而不是硬编码。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-26 22:53:52

既然你说它只会有一个层次的深度,那么你就不需要一个“深”的副本了。听起来,您只需要测试字符串是否可以使用JSON.parse,如果可以的话,只需要在对象中包含它们的键/值对。

如果是这样的话,一次简单的尝试/捕捉就可以了。您还可以在JSON.parse之后添加另一个检查,以验证解析的输出实际上是一个对象,或者筛选出某些键值,等等。

代码语言:javascript
复制
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);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52030570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档