user13146150
user13146150

Reputation:

Cannot convert undefined or null to object when iterating through valid JSON

I have valid JSON with this structure

const myJSONExample = {
  "SubItems": [
    {
      "SubItems": [
        {
          "ItemNo": "000001"
        }
      ],
      "ItemNo": null,
      "Number": null,
      "price": 114.46

    },
    {
      "SubItems": [
        {
          "Group": "0.4.004"
        }
      ],
      "type": null
    },
    {
      "SubItems": [
        {
          "ItemNo": "000005"
        },
        {
          "Quantity": 2
        }
      ],
      "Material": "Steel"
    },
    {
      "Description": null
    }
  ]
}

and just simply trying to format all number types in it, using recursive iteration.

const iterate = (obj) => {
    Object.keys(obj).forEach(key => {

    if(typeof(item[key]) == "number"){
                            item[key] = new Intl.NumberFormat("de-DE").format(item[key]) //format number for german lang.
                        }

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
        }
    })
}

iterate(myJSONExample);

I used this functions on other JSONs, and been trying to understand for some time, why this throws TypeError: Cannot convert undefined or null to object

Upvotes: 0

Views: 193

Answers (1)

epascarello
epascarello

Reputation: 207521

null is an "object" hence your issue. So add a truthy check

const iterate = (obj) => {
  Object.keys(obj).forEach(key => {

    const value = obj[key]
    const valueType = typeof value

    if (valueType === "number") {
      obj[key] = new Intl.NumberFormat("de-DE").format(value)
    } else if (valueType === 'object' && value) {
      iterate(value)
    }
  })
}

Upvotes: 2

Related Questions