I was given the assignment to create a function that, given an object and a key, returns an array containing all the elements of the array located at the given key that are less than 100. I came up with this:
function getElementsLessThan100AtProperty(obj, key) {
var lessThan100 = [];
var targetedKey = obj[key];
if (targetedKey === undefined) {
return [];
}
for (i = 0; i < targetedKey.length; i++) {
if (targetedKey[i] < 100) {
lessThan100.push(targetedKey[i]);
}
}
return lessThan100;
}
Now this works, but I am wondering why my original code didn't. I tried to loop over the array at the given property by writing the code below, but it didn't work. Why can't i do this? Also, would someone show me how to clean up this code to make it shorter?
for (i = 0; i <obj[key].length; i++) {
if (obj[key[i]].length < 100) {
lessThan100.push(obj[key[i]]);
}