1

I have an object with several sub-objects and I would like to retrieve all elements. When running the following code, I only retrieve part of the elements till the 'age'

 var output = '';
    
    var main_table = {
      animal: 'dog',
      color:'black',
      age: {
                year:2016,
                month:11,
                day:1
            },
      race:'sheepdog',
      parents: {
                father:'Dad',
       mother:'Mom'
            }
};
    
function test(main_table){
    table=main_table;
    for (var name in table) {
      if (table.hasOwnProperty(name)) {
        if (table[name]=="[object Object]") {
          test(table[name]);
        }
        else {
          output+=(name+' : '+table[name]+' ');
        }
      }
    }
    alert (output);
}

test(main_table)

Some help on it will be highly appreciated.

Nitheesh
  • 19,238
  • 3
  • 22
  • 49
superapi
  • 23
  • 3
  • 1
    Possible duplicate of [Iterate through Nested JavaScript Objects](http://stackoverflow.com/questions/8085004/iterate-through-nested-javascript-objects) – Weedoze Nov 04 '16 at 11:02

3 Answers3

2

You had created an implicit global variable with this line:

table=main_table;

by missing out the var.

I have also refactored a little bit to return the output at each recursive stage, and alert at the end.

var main_table = {
      animal: 'dog',
      color:'black',
      age:
      {
              year:2016,
              month:11,
              day:1
            },
      race:'sheepdog',
      parents:
         {
                father:'Dad',
       mother:'Mom'}
      };
    
function test(main_table){
    var table=main_table;
    var output = '';
    for (var name in table)
    {
      if (table.hasOwnProperty(name))
      {
        console.log(name, typeof table[name])
        if (typeof table[name]== "object")
        {
          output+=test(table[name]);
        }
        else
        {
          output+=(name+' : '+table[name]+' ');
        }
      }
    }
    return output;
}

alert(test(main_table))
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

I suggest to use an iterative, over the keys and recursive, over the children, approach, with a proper check

if (object[key] !== null && typeof object[key] === 'object') { //...

for iterable objects.

Methods used:

function getElements(object) {
    var result = [];
    Object.keys(object).forEach(function (key) {
        if (object[key] !== null && typeof object[key] === 'object') {
            result = result.concat(getElements(object[key]));
            return;
        }
        result.push([key, object[key]]);
    });
    return result;
}

var main_table = { animal: 'dog', color: 'black', age: { year: 2016, month: 11, day: 1 }, race: 'sheepdog', parents: { father: 'Dad', mother: 'Mom' } };

console.log(getElements(main_table));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Hi you set a wrong scope to your function because of this line table=main_table;

this code will work i suppose :

    var output = '';

var main_table = {
        animal: 'dog',
        color:'black',
        age:
            {year:2016,month:11,day:1},
        race:'sheepdog',
        parents:
            {father:'Dad',
            mother:'Mom'}
        };

function test(table){
for (var name in table)
    {
    if (table.hasOwnProperty(name))
        {
        if (table[name]=="[object Object]")
            {
            test(table[name]);
            }
        else
            {
            output+=(name+' : '+table[name]+' ');
            }
        }
    }
alert(output);
}

test(main_table);