Home > Net >  I am unable to add a new property to existing json
I am unable to add a new property to existing json

Time:09-10

Here is the function when I save the data on a click on save button, it collect all the data from the form and set it in json and save.

function traverseData(data, obj, newValue)
  {
      for (var k in data)
      {
          if (data.hasOwnProperty(k) && typeof data[k] == "object") {
              data[k] = traverseData(data[k], obj, newValue);
              console.log("k=" k ", obj=" obj);
          } else if (k == obj) {
            data[k] = newValue;
          }
      }
      return data
  }

This is the json in which i am trying to add the property

{
    "invoice":
    {
        "ocrData":
        {
            "invoiceNumber":"FM334J",
            "paymentDate":"Feb 24 , 2022",
            "sellerName":"Q FOTURE LTD",
            "sellerPhone":"  004154",
            "sellerAddress":"ROOM 1010",
            "sellerEmail":"",
            "sellerFax":"0088960",
            "sellerWebsite":"",
            "bankName":"S P DEVELOPMENT BANK",
            "bankAccountNumber":"00819",
            "bankAddress":"bank address",
            "ibanCode":"",
            "swiftCode":"SP0",
            "paymentCurrency":"USD",
            "paymentAmount":"60.00",
            "buyerName":"C TRADING",
            "buyerAddress":"44 AVE",
            "buyerWebsite":"website",
            "buyerAccountNumber":"0000819",
            "portOfLoading":"Casmora",
            "shipmentDate":"",
            "destination":"DAKAR",
            "currencySettlement":"XOF"
        },
        "products":
        [
            {
                "productDescription":"1 * 25KG BAG , 2FCL"
            }
        ],
        "results":
        [
            {
                "line":
                [
                    {
                        "field":"seller_phone",
                        "fieldValue":"  008154"
                    },
                    {
                        "field":"invoice_number",
                        "fieldValue":"FM334J"
                    },
                    {
                        "field":"buyer_name",
                        "fieldValue":"C TRADING"
                    },
                    {
                        "field":"seller_name",
                        "fieldValue":"Q FOTURE LTD"
                    },
                    {
                        "field":"seller_name",
                        "fieldValue":"Q FOTURE LTD"
                    },
                    {
                        "field":"seller_fax_number",
                        "fieldValue":"008960"
                    },
                    {
                        "field":"invoice_date",
                        "fieldValue":"Feb 24 , 2022"
                    },
                    {
                        "field":"buyer_address",
                        "fieldValue":"44 AVE"
                    },
                    {
                        "field":"seller_address",
                        "fieldValue":"ROOM 1010"
                    },
                    {
                        "field":"seller_address",
                        "fieldValue":"NO.I, DAO"
                    },
                    {
                        "field":"currency",
                        "fieldValue":"USD"
                    },
                    {
                        "field":"bank_account_number",
                        "fieldValue":"6000819"
                    },
                    {
                        "field":"seller_website",
                        "fieldValue":"www.fotoup.com"
                    },
                    {
                        "field":"invoice_amount",
                        "fieldValue":"60000"
                    },
                    {
                        "field":"bank_name",
                        "fieldValue":"SHA DEVELOPMENT BANK"
                    },
                    {
                        "field":"table",
                        "fieldValue":"table"
                    }
                ],
                "tableItem":
                [
                    {
                        "tableItem":"Description",
                        "tableItemValue":"1 * 25KG BAG , 2FCL"
                    }
                ]
            }
        ]
    }
}

Now this json doesn't contains the "paymentTerms" property to ocr data. I am trying to add that after "destination", I really appreciate if anyone can help.

CodePudding user response:

Assumption: code has parsed JSON text string representations of object data before accessing it in JavaScript.

Analyzing the traverseData code, it appears to

  • Attempt to find nodes in an object structure (the outermost data argument value) with an own property key matching a key string value passed as the obj argument.
  • If existing matching named properties are found, their value are updated to newValue.
  • If no matching property names are found, traverseData returns without making changes.
  • Property names would need to be unique among root and all sub-objects within the data structure to prevent multiple object properties being updated in a single call. Updating all copies of the same property name could, however, be a design objective and deliberate.

In addition

data[k] = traverseData(data[k], obj, newValue);

is setting data[k] to its existing value upon return from a recursive call. Should it be necessary the return value of traverseData could be used to return other values, such as a boolean indication of whether a property has been updated or not.


Different ways of adding a new property to the ocrData object include

  • adding it as a field to all existing ocrData data objects in a data base used to save and retrieve records to recreate the object model posted in the question,

  • if it doesn't already exist, add it with a default value to the parsed JSON data in JavaScript before calling traverseData, e.g.:

        const dataRoot = JSON.parse(/*JSON text*/);
        const defaultPaymentTerms = ""; // some chosen default
        if( !dataRoot.invoice.ocrData.hasOwnProperty("paymenTerms")) {
            dataRoot.invoice.ocrData.paymentTerms = defaultPaymentTerms;
        }
        ...
        traverseData( dataRoot, "paymentTerms", "30 days"); // update record.
    

This answer does not look into how to insert a property at a specific place in the (ES6) order of object properties. However, JSON implementations need not respect object property ordering, making the question of it largely academic. See "Is the order of elements in a JSON list preserved?" for discussion.

  • Related