javascript - 从点字符串中提取嵌套的 JSON。分配嵌套对象属性时遇到问题
问题描述
从嵌套点结构中提取 JSON 对象时,我在将属性分配给它时遇到问题。我得到了正确的第一级(例如billToCustomer
下面),但没有charges.chargeComponents
正确提取。我究竟做错了什么?
这是我的输出目标:
{
SourceScheduleNumber: '1',
charges: [
{
PricedQuantity: '2',
chargeComponents:[ <<<<not showing up in chargeComponents as expected
{
ChargeListCurrencyCode: 'USD',
ChargeDiscountUnitPrice: '-10'
}]
}
],
billToCustomer: [
{
PartyName: 'Test Knock One Back Liquors',
AccountNumber: '81010'
}
]
}
到目前为止我得到的代码片段:
let obj = {
SourceScheduleNumber: "1",
"charges.PricedQuantity": "2",
"charges.chargeComponents.ChargeListCurrencyCode": "USD",
"charges.chargeComponents.ChargeDiscountUnitPrice": "-10",
"billToCustomer.PartyName": "Test Knock One Back Liquors",
"billToCustomer.AccountNumber": "81010",
};
Object.keys(obj)
.filter((k) => k.includes("."))
.forEach((k) => {
let oo = ensureKeys(k, obj);
console.log(oo);
delete obj[k]; //remove the string prop
Object.entries(oo).forEach(([k, v]) => {
//console.log(k, v);
if (!obj[k]) obj[k] = [{}];
if (typeof v[Object.keys(v)[0]] === "object") {
let child = Object.keys(v)[0];
//console.log(`assigning `, v, `to `, obj[k][0], " child ", child);
Object.assign(obj[k][0], v[child]);
} else {
//top level param
//console.log(`assigning `, v, `to `, obj[k][0]);
Object.assign(obj[k][0], v);
}
console.log("step result:", obj[k][0], `\n----`);
});
});
console.log(obj);
//https://stackoverflow.com/a/7640970/1634753 <<modified by me to set value
function ensureKeys(str, res) {
let obj = {};
for (
var parts = str.split("."), i = 0, l = parts.length, cache = obj;
i < l;
i++
) {
if (!cache[parts[i]]) {
cache[parts[i]] = {};
}
//last item in chain
if (i + 1 === l) cache[parts[i]] = res[str]; //set the value
cache = cache[parts[i]];
}
return obj;
}
解决方案
推荐阅读
- delphi - LiveBindings TObjectBindSourceAdapter
- r - R - 在创建具有列名的新变量时合并数据框
- c++ - C ++从输入文件读取到结构数组
- javascript - 组件事件处理程序接收列表中不同组件的道具
- roblox - Roblox:BindToClose 有效,PlayerRemoving 无效
- pandas - matplotlib 问题:如何擦除这个?
- php - Symfony - 进程运行抛出异常 - 在命令行上执行有效
- c# - 在 C# 中使用 ExtraParams 从 Stripe 的 API 中提取特定事件
- arrays - 根据条件切片,否则返回空数组
- r - 有没有办法通过 r 代码选择 Shift F3