Home > database >  Trying to push the contents of objects nested inside objects to an array (JavaScript)
Trying to push the contents of objects nested inside objects to an array (JavaScript)

Time:11-25

When having objects nested inside objects I can't loop through them with a regular for in loop. I googled and found I have to make a recursive function that would check if the property is an object. I wrote a recursive function like this: `

 function isObject(value){
        return (typeof(value)==='object');
      }

``

 function listToArray(list){
        let arr=[];
        for (let elem in list){
            if(isObject(list[elem])===false){
                console.log(list[elem]);
            }
            else if (isObject(list[elem])){
                listToArray(list[elem]);
            }
        }
        return arr;
       }

`

this function works well, it loops deeply through all objects nested inside objects and console.logs all properties values. and returns an empty array.

however, when I replace console.log(list[elem])) with arr.push(list[elem]) to make the actual functionality works it pushes only the properties that are not objects in the first bigger object.

This is a coding problem in the book Eloquent JavaScript. I don't want an answer to this problem (in fact the book provides answers) I just want to know why did console.log works and arr.push don't. because it seems so weird to me and I can't find an explanation to that.

Edit: for Example this object

let list = { value : 1,
             rest: { value:2,
                     rest:{value:3,
                           rest:null}
                    }
            }

listToArray(list) should return [1,2,3]

CodePudding user response:

It's because you're not capturing the returned array in your elseif block

      function isObject(value){
        return (typeof(value)==='object');
      }
      
       function listToArray(list){
        let arr=[];  
        for (let elem in list){
            if(isObject(list[elem])===false){
                arr.push(list[elem]);
            }
            else if (isObject(list[elem])){
                retArr = listToArray(list[elem]);
                arr = [...arr, ...retArr];
            }
        }
        return arr;
       }
  • Related