简体   繁体   中英

How do I loop over an array at a given key on an object?

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]]);
    }

Because obj[key[i]] has to be obj[key][i] , additionally you check if the length is smaller 100 which is probably not your intention.

The whole code could be written as:

 const getLessThanHundred = (obj, key) =>
   obj[key].filter(it => it < 100);

在您修改后的代码中,您正在检查数组中项目的长度是否小于 100,而不是项目的是否小于 100。您应该检查(即 < 100;而不是 .length < 100)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM