首页 > 解决方案 > 从点字符串中提取嵌套的 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;
}

标签: javascriptjsondestructuring

解决方案


推荐阅读