0

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?

hallucinations
  • 3,424
  • 2
  • 16
  • 23
arjary
  • 169
  • 1
  • 12

1 Answers1

1

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.

arjary
  • 169
  • 1
  • 12
  • 1
    You don't need to clone the object. `set` isn't working on the nested `department` object because it's not a Backbone model. You could have just done `model.get('departments').head = 'abc';` but no events would be fired. – Emile Bergeron Dec 19 '17 at 18:30
  • I need the proper events to be fired. So doing what you told wont work for me. – arjary Dec 19 '17 at 20:26
  • That's what I explain in details in the [linked answer](https://stackoverflow.com/a/41701463/1218980). – Emile Bergeron Dec 19 '17 at 20:56
  • 1
    Ah, now i see the answer !. Thank you @EmileBergeron – arjary Dec 19 '17 at 21:02