简体   繁体   中英

Error : Uncaught TypeError: Cannot read property 'city' of undefined and How can I include a dash in an object key in javascript?

I am tryng to use json file . This code work ok on my code

 console.log(resp);

This is result of console

{Result: {…}}
Result:
Code: "00"
city: Array(18)
0: {cityname: "강원도", citycount: "146"}
1: {cityname: "경기도", citycount: "1055"}
2: {cityname: "경상남도", citycount: "303"}

But this isn't work

  console.log(itemNm2);
  console.log(dataV);

And this is the error!

Uncaught TypeError: Cannot read property 'city' of undefined

Also original code has variable like this 'city-name', 'city-count'

but it didn't work well . I think because of a dash? So I deleted a dash.

How can I solve this problem? thanks!!

This is my entire code:

$.ajax({
    url: 'js/map.json',
    type: 'GET',
    dataType: 'json',
    success: function (resp) {
        console.log(resp);
        var options = {
            toolTip : {
                use : {
                    local : true
                },
                className : 'tip',
                position : {
                    x : 0,
                    y : -10
                }
            },
            data: {
                data: [
                    {locname: '', listshrs: ''}
                ],
        localOption: 'locname',
        use : 'listshrs'
            }
        };
        var rows = resp.Result[1].City;
        if (rows) {
            var representativeRow;
            for (i = 0; i < 2; i++) {
                representativeRow = rows[i];
                itemNm2 = representativeRow.cityname;
                dataV = representativeRow.citycount;
                console.log(itemNm2);
                console.log(dataV);
                options.data.data.push({locname: itemNm2, listshrs: dataV});
            }


            korea = webponent.visual.korea.init($(".korea"), style, options);

        }


    }, error: function (xhr, status, error) {
        alert("err")
    }
});

this is examples of json!

{
  "Result": {
    "Code": "00",
    "City": [
      {
        "city-name": "강원도",
        "city-count": "146"
      },
      {
        "city-name": "경기도",
        "city-count": "1055"
      }
    ]
  }
}

try this:

itemNm2 = representativeRow["city-name"];
dataV = representativeRow["city-count"];

From what I can see in your example JSON and your code, you're trying to access resp.Result[1].City but resp.Result is not an array. Instead of :

var rows = resp.Result[1].City;

You have to do this:

var rows = resp.Result.City;

Also, if you must use dashes in your JSON object, see Charis Theo's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM