I am having issues assigning properties to a JSON object when extracting it from a nested dot structure. I get the first level right (eg billToCustomer below) but don't extract charges.chargeComponents correctly. What am I doing wrong?
This is my output goal:
{
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'
}
]
}
Code snippet of where I got so far:
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;
}