1

I have a json object containing information about a person, and I want to update the data using jQuery extend function, the problem is that the child gets rewritten.

example:

var dadThen = {
  name: "Adam",
  age: 35,
  child:{
    name: "Ben",
    age: 10
  }
}

// dad now
var dadNow = {
  age: 36,
  child: {
    age: 11
  }
}

var newData = $.extend({}, dadThen, dadNow);
// The child name gets removed
// newData.child.name is undefined

How to fix this?

Bouh
  • 1,303
  • 2
  • 10
  • 24
  • nitpick: You dont have a "JSON object" you have a javascript object. JSON would be a string, and would have quotes round the keys. – Jamiec Jul 20 '20 at 16:35
  • 1
    change your `{}` to `true` like this `var newData = $.extend(true, dadThen, dadNow);` because true tells jquery to do deep copy – henok Jul 20 '20 at 16:41

1 Answers1

1

Isnt it like this

var newData = $.extend(true, {}, dadThen, dadNow);

first parameter is a flag whether to deep clone the object.

kiranvj
  • 32,342
  • 7
  • 71
  • 76