Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there are proper way to $.extend a nested properties in jQuery?

What I have and what I need. It's easy.

The default options (there are nested properties):

{
  sDom: 'frt<"tfoot"lp>',
  bInfo: false,
  sPaginationType: "full_numbers",
  oLanguage: {
    sSearch: "",
    sLengthMenu: "Show _MENU_",
    oPaginate: {
      sFirst:     "|<<",
      sLast:      ">>|",
      sNext:      ">>",
      sPrevious:  "<<"
    }
  }
}

Actual options:

{
  oLanguage: {
    oPaginate: {
      sNext:      "MODIFIED"
    }
  }
}

The result of $.extend:

{
  sDom: 'frt<"tfoot"lp>',
  bInfo: false,
  sPaginationType: "full_numbers",
  oLanguage: {
    oPaginate: {
      sNext:      "MODIFIED"
    }
  }
}

What I need is to properly extend the defaults options with the actual options and get the following result (one property has been modified):

{
  sDom: 'frt<"tfoot"lp>',
  bInfo: false,
  sPaginationType: "full_numbers",
  oLanguage: {
    sSearch: "",
    sLengthMenu: "Show _MENU_",
    oPaginate: {
      sFirst:     "|<<",
      sLast:      ">>|",
      sNext:      "MODIFIED"
      sPrevious:  "<<"
    }
  }
}

The problem is that $.extend function ignores nested properties and operates only first-level properties. Now I have manually $.extend each of the nested properties, but I guess it is not a solution.

like image 329
odiszapc Avatar asked Jun 05 '12 05:06

odiszapc


1 Answers

You need a recursive copy by passing true as the first parameter:

var defaults = {...}
var actual = {...}

//recursively merge to a blank object
console.log($.extend(true,{}, defaults, actual))​
like image 75
Joseph Avatar answered Nov 05 '22 05:11

Joseph