简体   繁体   中英

jQuery JSON Array undefined / not an object

As a Javascript novice, I'm having a hard time figuring out the following issue:

I have an external JSON file with a list of colors.

[
{"num": "1B2-5","nam": "burntsienna","hex": "EA7E5D","com": "int2"},
{"num": "1B3-5","nam": "cadetblue","hex": "5F9EA0","col": "int1"},
{"num": "1B1-6","nam": "chartreuse","hex": "7FFF00"},
{"num": "1B2-6","nam": "chocolate","hex": "D2691E","com": "int2"}
]

At this point in the code, the background-color value of #background will be equal one of the values in the JSON file. I convert the background-color value to hex, remove the '#' character, and find its index number in the JSON array. I then declare variables for the corresponding properties using the index number.

I have shortened the code for the purpose of this example.

$(document).ready(function() {
$.getJSON('_js/json.js', function(colors_list){ 

    var pageColorPre = rgb2hex($('#background').css('background-color'));
    var pageColor = pageColorPre.toUpperCase().substr(1);
    var pageColorIndex = findIndexByKeyValue(colors_list, "hex", pageColor)

    var nameByIndex = colors_list[pageColorIndex].nam
    var numberByIndex = colors_list[pageColorIndex].num
    var comByIndex = colors_list[pageColorIndex].com


function findIndexByKeyValue(obj, key, value){
    for (var i = 0; i < obj.length; i++) {
        if (obj[i][key] == value) {
        return i;
        }
      }
      return null;
}

function rgb2hex(rgb) {
 if (  rgb.search("rgb") == -1 ) {
      return rgb;
      } else {
      rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
      function hex(x) {
           return ("0" + parseInt(x).toString(16)).slice(-2);
      }
      return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
      }
}
});
});

Even though the code works well in Safari, Firefox, and Chrome, when the browser reaches this line:

  var numberByIndex = colors_list[pageColorIndex].num

I get the following errors when debugging:

uncaught TypeError: cannot read property 'nam' of undefined. 

The code breaks in IE8 with the following message:

'colors_list[...] nam'is null or not an object.

I thought perhaps since the "com" and "col" values are sometimes null, not every color has them, that might be an issue. However, I get the same error message even when only declaring a property such as "nam" or "num" which every color has.

Thanks.

Thought I would post this as new answer, as the previous answer was in reference to what seemed to be a typo in the question...

The error you're getting is actually in relation to the line:

var nameByIndex = colors_list[pageColorIndex].nam

This is why it's not reaching the next line in which you try to get the NumberByIndex . (By the way, you should be ending those lines with a semi-colon ; , to prevent further problems...)

The problem is with the object...

colors_list[pageColorIndex]

...in that it seems to be showing up as null. Since we "know" that colors_list (though it might be worth debugging to check) is a valid array, the problem must be with pageColorIndex which is originally returned by findIndexByKeyValue() ; it could be that findIndexByKeyValue is returning null.

It would be worth inserting the lines console.log(obj[i][key]) and console.log(value) above your conditional statement and checking what they look like in the console when you run the code again. Look in particular for unexpected spacing, before or after the hex value. You might find that the pageColor variable is not formatted as you expected it to be and therefore not matching with any of the hex values in your array objects and returning null.

Hope this helps.

Update - according to jcubic, this doesn't apply to JSON, so I'm retracting this answer.

Not sure if it's your whole problem, but you're not declaring objects right - keys aren't usually strings.

Instead of:

{"num": "1B2-5","nam": "burntsienna","hex": "EA7E5D","com": "int2"}

You want:

{ num: "1B2-5", nam: "burntsienna", hex: "EA7E5D", com: "int2"}

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