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?

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks,how to set the property value when the jsondata is not an array and it may be empty pls help
If it is not an array, what it is ?
sometimes the jsondata is like {"lName":"john","fName":"conor"} and {}
So, if jsonData is empty you don't want to alter the people array, but when jsonData is an object with properties you want add it to the people array ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.