开发者问题收集

为什么我在尝试设置 JSON 字段的值时会收到此错误?未捕获 TypeError:无法设置未定义的属性“today_avg_price”

2017-10-10
73

我不太懂 JavaScript,但我疯狂地尝试执行此脚本,从 JSON 文档开始创建另一个 JSON 文档:

(我将示例放入 html 文件中并在 Chrome 上调试它,您可以执行相同的操作来测试它):

<!DOCTYPE HTML>
<html>

<body>

  <p>Before the script...</p>

  <script>
    function checkForNull(value) {
        if (value instanceof Object && "@nil" in value) {
            return null;
        }

        return value;
    }

    console.log("START")

    var payload = JSON.parse(`
        {
            "Markets": {
                "Market": {
                    "market_name": "Tambacounda Market N1",
                    "market_description": "Tambacounda Market N1",
                    "localization_id": 2,
                    "long": 13.776796,
                    "lat": -13.672198,
                    "country": "Senegal",
                    "regione": {
                        "@nil": "true"
                    },
                    "province": {
                        "@nil": "true"
                    },
                    "city": {
                        "@nil": "true"
                    },
                    "district": {
                        "@nil": "true"
                    },
                    "town": {
                        "@nil": "true"
                    },
                    "village": {
                        "@nil": "true"
                    },
                    "commodity": {
                        "el": [{
                                "commodity_details_id": 4,
                                "commodity_name_en": "Red onion",
                                "commodity_name": "Red onion",
                                "image_link": "Red_onion.jpg",
                                "today_avg_price": 20.1500,
                                "yesterday_avg_price": 33.3300,
                                "currency": "XOF",
                                "measure_unit": "kilogram",
                                "price_series_id": 1
                            }, {
                                "commodity_details_id": 6,
                                "commodity_name_en": "Green Beans",
                                "commodity_name": "Green Beans",
                                "image_link": "Green_Beans.jpg",
                                "today_avg_price": {
                                    "@nil": "true"
                                },
                                "yesterday_avg_price": 778.0000,
                                "currency": "RWF",
                                "measure_unit": "kilogram",
                                "price_series_id": 17
                            }
                        ]
                    }
                }
            }
        }
    `);

    // create new response          
    var response = payload.Markets.Market;
    console.log("RESPONSE: " + JSON.stringify(response));

    // convert null values
    response.regione = checkForNull(response.regione);
    response.province = checkForNull(response.province);
    response.city = checkForNull(response.city);
    response.district = checkForNull(response.district);
    response.town = checkForNull(response.town);
    response.village = checkForNull(response.village);

    // convert array of commodities into required HATEOS format
    var commodity = new Array();

    for (i = 0; i < response.commodity.el.length; ++i) {
        var el = response.commodity.el[i];  
        var newEl = new Object();
        newEl.commodity_name = el.commodity_name;
        newEl.commodity.today_avg_price = el.today_avg_price;
        newEl.commodity.yesterday_avg_price = el.yesterday_avg_price;
        newEl.rel = "commodity_details";
        newEl.href = "http://5.249.148.180:8280/commodity_details/" + el.commodity_details_id;
        newEl.type = "GET";

        commodity.push(newEl);
    }

    response.commodity = commodity;


    console.log("END");
  </script>

  <p>...After the script.</p>

</body>

</html>

如您所见,原始文档位于 payload 对象中。

问题发生在 for 循环中第一次迭代的这一行:

newEl.commodity.today_avg_price = el.today_avg_price;

并给出此错误消息:

parse_json_market.html:97 Uncaught TypeError: Cannot set property 'today_avg_price' of undefined
at parse_json_market.html:97

如您所见,此 JSON 字段包含 20.1500

"today_avg_price": 20.1500,

为什么?有什么问题?我遗漏了什么?我该如何解决这个问题?

3个回答

您只需要在 newEl.commodity.today_avg_price 之前添加此代码即可。

newEl.commodity = new Object();

原因是 newElobject ,但 newEl.commodityundefined 。 因此,您必须在调用 newEl.commodity.today_avg_price 之前将 newEl.commodity 设置为对象。

FIDDLE

artgb
2017-10-10

因为 commodity 对象不存在于新创建的 newEl 对象中。 这就是为什么它给出错误 commodity 现在未定义,并且无法在未定义上设置属性。

因此,您所要做的就是在设置任何属性之前,先创建一个空对象,例如 newEl.commodity = {

ricky
2017-10-10

我假设 newEl.commodity_name = el.commodity_name; 有效,因为您在上一行创建了一个对象。

但您尚未创建商品对象。例如...

var newEl = new Object();
newEl.commodity_name = el.commodity_name;

var commodityObj = new Object();
commodityObj.today_avg_price = el.today_avg_price;

newEl.commodity = commodityObj;
Chris Adams
2017-10-10