Search code examples
javascriptobjectstring-concatenationconsole.logstring-conversion

How do I print an objects iterated children in javascript?


I have Object:

[Object]
    0: {Class: "MTH 1100-A", __rowNum__: 1}
    1: {Class: "CSC 3200-B", __rowNum__: 2}
    2: {Class: "ART 4334-E", __rowNum__: 3}
    3: {Class: "REC 3223-C", __rowNum__: 4}

I would like to get all of these into an array, before I do that though I was just simply trying to print them and I cant even seem to do that. Here is the code I have:

const obj = {
  0: { Class: "MTH 1100-A",__rowNum__: 1},
  1: { Class: "CSC 3200-B", __rowNum__: 2 },
  2: { Class: "ART 4334-E", _rowNum__: 3 } ,
  3: { Class: "REC 3223-C", _rowNum__: 4 }
};

function getDescendantProp(obj, desc) {
  var arr = desc.split(".");
  while (arr.length && (obj = obj[arr.shift()]));
  return obj;
}

console.log(getDescendantProp(obj, '0.Class'));

for (var i = 0; i < obj.length; i++) {
  console.log(getDescendantProp(obj, "\'" + i + ".Class\'"));
}

For output you get:

"MTH 1100-A"
Undefined
Undefined
Undefined
Undefined

So why cant I get those values.....?


Solution

  • There are some issues with your code.

    1. The line you se printed belongs to the first console.log() call. In there you pass '0.Class', which you don't do on the console.log() calls inside the for loop. In there this should suffice getDescendantProp(obj, i + ".Class"). No need to escape the quotes.
    2. Your condition in your while loop seems very strange to me. By using the = operator you're assigning the right side of the expression to obj, thus, replacing the original value of obj by obj[arr.shift()]. If obj[arr.shift()] happens to be not null, which happens on the first iteration of the while loop, and the condition passes. Then you return obj which has become the value you were looking for. I have to say, I find it an ingenious way to find the object property you're looking for, but a bit over engineered. For comparisons you should use == or ===.

    I modified a bit your code so it works and added a few variables to be able to track what's going on:

        var obj = {
            0: {Class: "MTH 1100-A", __rowNum__: 1},
            1: {Class: "CSC 3200-B", __rowNum__: 2},
            2: {Class: "ART 4334-E", __rowNum__: 3},
            3: {Class: "REC 3223-C", __rowNum__: 4}
        }
    
        function getDescendantProp(obj, desc) {
            var arr = desc.split(".");
            var arrCopy = arr.slice();
            arrCopy = arrCopy.shift();
            while(arr.length && (obj = obj[arr.shift()])){
                var bla = "bla";
            };
            return obj;
        }
    
        for(var i = 0; i< Object.keys(obj).length; i++) {
            var o = getDescendantProp(obj,  i + ".Class");
            console.log(o);
        }
    

    However, mind that you can access an object properties either like this obj.property or obj["property"]. With this in mind this can be further simplified to the following:

        var descendantsArray = [];          // Array to put each desired element from obj
        var objKeys = Object.keys(obj);     // Array with the keys to the object
    
        for (var i = 0; i < objKeys.length; i++) {
            var currentKey = objKeys[i];                    // Get current key
            var currentElement = obj[currentKey];           // Get the element that corresponds to the key
            descendantsArray.push(currentElement.Class);    // Add the current element's Class property to the Array
            console.log(currentElement.Class);              // Print the 'Class' property of the current element
        }
    

    Cheers