Backbone model.set on a nested object in the response

261 views Asked by At

I have an API response that has a nested object like below -

{
    name: '',
    age: '',
    departments: {
        size: '',
        head: ''
    }

}

How do I set the head attribute of the departments object?

I tried doing the below

model.get('departments').set({
    head: 'abc'
})

this throws an error model.get(...).set is not a function.

EDIT:

tried doing -

 model.set('departments', {'head': 'abc'});

This will set the head attribute in the departments object. However, it rips off the size attribute from the departments object in the response.

Is there a better way to do this? What am I missing?

1

There are 1 answers

4
arjary On

I was able to achieve this using the clone function from underscore. Below is the solution -

  var departmentObj = _.clone(model.get('departments'));
      departmentObj.head = 'abc';
      model.set({
        'departments': departmentObj
      });

This should do the job.