【freecodecamp】练习题Where art thou 对象数组比较 返回有相同属性值的数组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/towrabbit/article/details/80349451

题目需求:

写一个 function,它遍历一个对象数组(第一个参数)并返回一个包含相匹配的属性-值对(第二个参数)的所有对象的数组。如果返回的数组中包含 source 对象的属性-值对,那么此对象的每一个属性-值对都必须存在于 collection 的对象中。

例如,如果第一个参数是 [{ first: “Romeo”, last: “Montague” }, { first: “Mercutio”, last: null }, { first: “Tybalt”, last: “Capulet” }],第二个参数是 { last: “Capulet” },那么你必须从数组(第一个参数)返回其中的第三个对象,因为它包含了作为第二个参数传递的属性-值对。

规划

遍历要检查的对象数组for循环,
在循环中,首先获取要检查的对象source key有哪些,
键值只要有一个不对应跳出for循环,如果没有跳出循环那说明键值对应符合,
在返回的对象数组中添加符合条件的对象

代码

function where(collection, source) {
  var arr = [];
  for(var i = 0 ; i < collection.length ; i ++ ){
  //获取要比较的对象的key值数组并储存
    var Keys = Object.keys(source);
    var hasKeysAndRightValue = true;//先假设键值对应是对应的
    for(var j = 0 ; j < Keys.length ; j ++ ){
      if (source[Keys[j]] !== collection[i][Keys[j]]){
        hasKeysAndRightValue = false;
        break;//只要有一个不对应就跳出循环
      }
    }
    if(hasKeysAndRightValue)arr.push(collection[i]);//将键值对应的数组添加到要返回的新数组中
  }
  return arr;
}
where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

猜你喜欢

转载自blog.csdn.net/towrabbit/article/details/80349451