尝试复制一个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: '' }我不知道什么数据将来自DB,但是每当它包含字符串时,我都可以硬编码它,以便从json中的字符串中获取特定的值。试过深拷贝,但做不到。这并不是说我还没有尝试完成这个任务,但我无法想出一种方法来使它变得更通用,而不是硬编码。任何帮助都将不胜感激。
发布于 2018-08-26 22:53:52
既然你说它只会有一个层次的深度,那么你就不需要一个“深”的副本了。听起来,您只需要测试字符串是否可以使用JSON.parse,如果可以的话,只需要在对象中包含它们的键/值对。
如果是这样的话,一次简单的尝试/捕捉就可以了。您还可以在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);
https://stackoverflow.com/questions/52030570
复制相似问题