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.....?
There are some issues with your code.
getDescendantProp(obj, i + ".Class")
. No need to escape the quotes.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