0

In the html page i have a view model

 AppViewModel = {
        people : ko.observableArray([
        {
            fName : 'john'
            lName :'conor'
        }, {
            city  : 'dallas'
        }, {
            state : 'texas'
        } ]),


    };

and i fetch the json data from the server in the format

{
                fName : 'john'
                lName :'conor'
            }, {
                city  : 'dallas'
            }, {
                state : 'texas'
            }

i want the json data to get added to the array(push), anything like AppViewModel.people.push(ko.mapping.fromJS(jsondata, viewModel)) but it is not working. Any ideas?

Bhaskar
  • 143
  • 1
  • 6
  • 18
  • possible duplicate of [Map JSON data to Knockout observableArray with specific view model type](http://stackoverflow.com/questions/9951521/map-json-data-to-knockout-observablearray-with-specific-view-model-type) – PW Kad Aug 13 '13 at 16:10
  • why ko.mapping.fromJS is not working?? please post a jsfiddle example – ebram khalil Aug 13 '13 at 17:44

1 Answers1

3

If jsonData is an array, this works.

ko.utils.arrayForEach(jsondata, function(item){
    AppViewModel.people.push(item);
});

Edit

You can check if the object is not empty by using jQuery.isEmptyObject.

if(jQuery.isEmptyObject(jsonData) == false)
    AppViewModel.people.push(jsonData)

Or you can use this version of isEmpty :

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}

I hope it helps.

Damien
  • 8,889
  • 3
  • 32
  • 40