使用 for 循环而不是过滤器

using for loop instead of filter

Make a function that looks through an array of objects (first argument) and returns an array of all objects that have a matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.

这是 freecodecamp 上的一个挑战,我很难仅使用 for 循环为其编写代码。我可以让它与 filter() 和 for 循环一起工作,但我想看看如果我们使用 if 语句和 for 循环它会怎样。有人可以帮我吗?

代码:(使用过滤器)

function whatIsInAName(collection, source) {
  // "What's in a name? that which we call a rose
  // By any other name would smell as sweet.”
  // -- by William Shakespeare, Romeo and Juliet
  var srcKeys = Object.keys(source);

  // filter the collection
  return collection.filter(function(obj) {
    for (var i = 0; i < srcKeys.length; i++) {
      if (
        !obj.hasOwnProperty(srcKeys[i]) ||
        obj[srcKeys[i]] !== source[srcKeys[i]]
      ) {
        return false;
      }
    }
    return true;
  });
}


//input
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })

//output
[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]

不使用过滤器(我的方法):

function whatIsInAName(collection, source) {
  let n=[]
  arrayOfSrc=Object.keys(source) // contains the array of properties of source
  for(let obj of collection){
    for(let propName of arrayOfSrc){
      //if obj hgas the property and the value of the property also matches
      if(obj.hasOwnProperty(propName) && source[propName]==obj[propName]){
        //push the matched object to n
       n.push(obj)
      }
    }
  }
  console.log(n)
return n
  
}

请使用此代码。

  let result=[]
  arrayOfSrc=Object.keys(source)
  for(let obj of collection){
    let count = 0;
    for(let propName of arrayOfSrc){
      if(obj.hasOwnProperty(propName) && source[propName]==obj[propName]){
        count++;
      }
    }
    if(result.indexOf(obj) == -1 && count == arrayOfSrc.length) result.push(obj)
  }
  return result