arrays - 深拷贝 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 中的字符串中获取特定值。尝试过深拷贝,但无法正确完成。这并不是说我没有尝试过完成这项工作,而是无法想出一种方法让它更通用而不是硬编码。任何帮助,将不胜感激。
解决方案
既然你说它只会是一个级别的深度,那么你真的不需要一个“深度”副本可以这么说。听起来好像您只需要测试字符串以查看它们是否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);
推荐阅读
- json - 基于 json 遍历结构数组导致预览失败
- android - 应用内计费:我们可以在应用内动态创建订阅吗?
- gradle - 使用 Gradle 在插件中配置 Zip/Copy 任务
- c++ - 为什么错误一直返回“变量的类型不完整”?
- linux - umask 值为 457 时,它应为 w, x, - 210 (666-457),但我将其视为 w,w,-..(220)。这是为什么?
- python - txt文件转换成数据框
- java - 为什么匿名类在 Java 中不能有静态成员(最终成员除外)?
- react-hooks - 优化自定义 React Hooks - 数据获取
- r - 如何将一列分成三个不同的列,然后从结果的两列中获取平均值(R)
- apache-spark - Pyspark 版本的 Amazon Deequ