Search code examples
javascriptjqueryknockout.jsinternet-explorer-8knockout-mapping-plugin

Converting JSON object to knockout observable not works in IE8, but works in all other browsers


I have following object

{
      "section_name": "Basic Info",
      "data": [
        {
          "jw_fullname": "John",
          "jw_email": "smith@gmail.com",
          "jw_phone": "12365489",
          "jw_website": "www.rcv.com",
          "jw_address1": "Test",
          "jw_address2": "T test",
          "jw_address3": "tesst,",
          "mtheme": "metro",
          "dtheme": "Bold"
        }
      ],
      "key": "basicinfo",
      "prevent": true
    }

I want everything inside it should be observable. So i pass 'data' into the 'convertToObservable' function to make everthing inside it to become observable.

   function convertToObservable(section)

    {

        var newSection = [];

        $.each(section, function (i, obj) {


            var newObj = {};

            Object.keys(obj).forEach(function (key) {

                console.log(key);

                newObj[key] = ko.observable(obj[key]);

            });

            newSection.push(newObj);

        });

        return newSection;

    }

This makes everything inside it observable and works perfect in all browsers except IE8.

In IE8 this line in function 'convertToObservable' fails

Object.keys(obj).forEach(function (key) {

I get this error only in IE8 " Object doesn't support this property or method"

Is it any way to make it work in IE8?


Solution

  • As noted here, Objects.keys is not available in IE8. A simple for in loop should work fine for you. Just be sure to filter out properties from further up the prototype chain with hasOwnProperty

    for (var key in obj){
        if (obj.hasOwnProperty(key)){
            newObj[key] = ko.observable(obj[key]);
        }
    }