2
\$\begingroup\$

I am using this for in loop to loop through a JSON object and to assign the JSON object's value to my own object in a KnockoutJS setup.

The JSON object looks like this:

[
    {
    categoryId: "013",
    categoryName: "Toys",
    id: 2328,
    name: "Megatron",
    summary: "",
    price: 120,
    extraInfo: {
        minAge: 3,
        maxAge: 7
    }
    },
    {
    categoryId: "014",
    categoryName: "Apparels",
    id: 2327,
    name: "Tank Top",
    summary: "",
    price: 70,
    extraInfo: {
        minAge: 5
        maxAge: null
    }
    }
]

And the for in loop goes inside the JSON object and then assign the JSON object's values to an existing object:

   function Item(data){
       var self = this;
       for(i in data){
       if(typeof data[i]==='object'){
           var dataObj = data[i];
           for(j in dataObj){
           self[j] = dataObj[j];
           }
       }
       else{
           self[i] = data[i];
       }
       }
   }

As you can see, I'm basically copying over the key values of the JSON object to an existing object, and if the value is an object, I copy the values too and assign them to the object.

This is already an improvement from an older version, where I basically copy over the keys manually, like:

self.someKey = data.someKey;

However, I can't help but feel this can be improved, particularly the part where I was checking for an object within the JSON object. I came from a web designer background and often find myself coding code that's not rigorous enough and breaks in cases I don't foresee. I hope doing this regularly will improve my code with time.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.