Let's say I have a Widget object that I serialize and send back to the browser at a regular interval. This Widget object includes lots of different members (variables) and other objects along with their members. For example, in PHP, my widget may look like this:

class Widget implements \JsonSerializable{
  private $_variable_1 = null;
  private $_variable_2 = null;
  private $_object_widget_child = null; //This is an array of widget children

For sake of brevity, the object Widget_child may have many members (variables) and objects.

I find it cumbersome to work with serialized objects in javascript when they are implemented in this way in PHP because I end up having to write javascript code to iterate through each array of serialized objects. Example in javascript:

success: function(data){
  var variable_1 = data.widget._variable_1;
  var variable_2 = data.widget._variable_2;

  var num_widget_children = data.widget._object_widget_child.length;
  if(num_widget_children > 0){
    for(var i = 0; i < num_widget_children; i++){
      //Do something like access widget childs name

I think you could see how this could become very cumbersome if the widget children also had arrays of objects as members of its class and I needed to access some property 5 levels deep.

Is this method of design the issue or is there an easier way to work with serialized objects from PHP in javascript that I need to research?

1 Answer 1


If you need to process nested arrays with known structure, you should create method which will process every level using recurency:

function myHelper(widget) {
    var result = {
        variable_1: widget._variable_1,
        variable_2: widget._variable_2,
        children: [],

    var num_widget_children = widget._object_widget_child.length;
    if (num_widget_children > 0){
        for (var i = 0; i < num_widget_children; i++){

    return result;
  • I don't know if I agree with using recursion as I think that would add unnecessary complexity. However, I do see a benefit to creating methods that would specifically handle nested objects. Apr 27, 2018 at 16:20
  • 1
    @larrylampco I'm not sure what kind of complexity you are talking about - this is directly the consequence of the DRY principle (all widget objects are processed by one method). Recursion is just a representation of nesting.
    – rob006
    Apr 27, 2018 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.