简体   繁体   English

在对象数组中搜索匹配的属性和值对

[英]Searching for matching property and value pairs in an array of objects

I am trying to solve a freeCodeCamp exercise and have gotten stuck.我正在尝试解决一个freeCodeCamp练习但被卡住了。 The goal of the exercise is this: Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument).练习的目标是:创建一个函数,它查看对象数组(第一个参数)并返回一个包含匹配属性和值对(第二个参数)的所有对象的数组。 Each property 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.如果要包含在返回的数组中,源对象的每个属性和值对都必须存在于集合中的对象中。

So what I did, was to make an array of the key pairs of the collection, and another array with the key pairs of the source.所以我所做的是制作一个集合的密钥对数组,以及另一个包含源密钥对的数组。 The I nested for-loops in order to find matching keys, and if those keys are found, then compare the properties. I 嵌套 for 循环以查找匹配的键,如果找到这些键,则比较属性。

But somehow, my code returns no matches.但不知何故,我的代码没有返回匹配项。

var collection = [{
  first: "Romeo",
  last: "Montague"
}, {
  first: "Mercutio",
  last: null
}, {
  first: "Tybalt",
  last: "Capulet"
}];
var source = {
  last: "Capulet"
};

var collectionKeys = [];
for (var i = 0; i < collection.length; i++) {
  collectionKeys.push(Object.keys(collection[i]));
}
var sourceKeys = Object.keys(source);

//for every key pair
for (var t = 0; t < collectionKeys.length; t++) {
  //for every key in key pair
  for (var x = 0; x < collectionKeys[t].length; x++) {
    //for every key in search
    for (var y = 0; y < sourceKeys.length; y++) {
      //see if a key matches
      if (sourceKeys[y] == collectionKeys[t][x]) {
        //see if the value matches
        if (collection[collectionKeys[t][x]] == source[sourceKeys[y]]) {
          console.log(collection[t]);
        } else {
          console.log("value not found");
        }
      } else {
        console.log("key not found");
      }
    }
  }
}

Can anybody point out what I'm doing wrong?谁能指出我做错了什么?

I've also created a JSfiddle if you want to tinker.如果你想修修补补,我还创建了一个JSfiddle

be more explicit in your declarations - helps to read the code easier:在您的声明中更加明确 - 有助于更轻松地阅读代码:

var sourceKeys = Object.keys(source),
    i = 0, 
    j = 0,
    collectionLength = collection.length,
    sourceKeysLength = sourceKeys.length;

while (i < collectionLength) {
    j = 0;
    while (j < sourceKeysLength) {
        if (sourceKeys[j] in collection[i] && source[sourceKeys[j]] === collection[i][sourceKeys[j]]) {
            console.log('found one!');
        }
        j++;
    }
    i++;
}

https://jsfiddle.net/fullcrimp/1cyy8z64/ https://jsfiddle.net/fullcrimp/1cyy8z64/

I was also stuck on this for a good hour, when I stumbled upon a couple resources to assist.当我偶然发现一些资源可以提供帮助时,我也被困在这个问题上一个小时。

I found that rather than the mess of nested for loops, I could use the built in looping methods to greatly simplify my code.我发现我可以使用内置的循环方法来大大简化我的代码,而不是一团糟的嵌套 for 循环。

here is where I found my explanation:这是我找到我的解释的地方:

https://github.com/Rafase282/My-FreeCodeCamp-Code/wiki/Bonfire-Where-art-thou https://github.com/Rafase282/My-FreeCodeCamp-Code/wiki/Bonfire-Where-art-thou

function where(collection, source) {
  var arr = [];
  var keys = Object.keys(source);
  // Filter array and remove the ones that do not have the keys from source.
  arr = collection.filter(function(obj) {
    //Use the Array method every() instead of a for loop to check for every key from source.
    return keys.every(function(key) {
      // Check if the object has the property and the same value.
      return obj.hasOwnProperty(key) && obj[key] === source[key];
    });
  });

  return arr;
}

Some insight here with clear understanding and less loops.这里有一些洞察力,具有清晰的理解和较少的循环。

some new javascript function like some, filter, map are really handy to make code tidier as well.一些新的 javascript 函数,如some、filter、map也非常方便使代码更整洁。

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  collection.some(function(obj){
      var sk = Object.keys(source); //keys of source object
      var sv = Object.values(source); //values of source object
      var temp = 0; 
      for(i=0;i<sk.length;i++){ // run until the number of source properties length is reached.
        if(obj.hasOwnProperty(sk[i]) && obj[sk[i]] === sv[i]){ // if it has the same properties and value as parent object from collection 
          temp++; //temp value is increased to track if it has matched all the properties in an object
        }
      }
      if(sk.length === temp){ //if the number of iteration has matched the temp value 
        arr.push(obj);
        temp = 0; // make temp zero so as to count for the another object from collection
      }
  })
  // Only change code above this line
  return arr;
}

 var collection = [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]; var source = { last: "Capulet" }; var collectionKeys = []; for (var i = 0; i < collection.length; i++) { collectionKeys.push(Object.keys(collection[i])); } var sourceKeys = Object.keys(source); //for every key pair for (var t = 0; t < collectionKeys.length; t++) { //for every key in key pair for (var x = 0; x < collectionKeys[t].length; x++) { //for every key in search for (var y = 0; y < sourceKeys.length; y++) { //see if a key matches if (sourceKeys[y] == collectionKeys[t][x]) { if (collection[t][collectionKeys[t][x]] == source[sourceKeys[y]]) { alert(collection[t].first+ " "+collection[t].last); } else { console.log("value not found"); } } else { console.log("key not found"); } } } }

Change collection[collectionKeys[t][x]] to collection[t][collectionKeys[t][x]].. collection[collectionKeys[t][x]] gives undefined in console.collection[collectionKeys[t][x]]更改为 collection[t][collectionKeys[t][x]].. collection[collectionKeys[t][x]]在控制台中给出undefined

This is what I came to on the same problem.这就是我遇到同样问题的原因。

function whereAreYou(collection, source) {
  // What's in a name?

  // Only change code below this line

  var arr = [];
  var validObject;

// check each object
  for  (var each_object in collection ){
    validObject = true;
    for (var key in source ){
      if ( collection[each_object].hasOwnProperty(key)){
        if ( collection[each_object][key] != source[key]){ 
       // if no valid key
       validObject = false;
     } 
   } else {
    // if no valid value
     validObject = false;
   }
 }
  // otherwise, give it a green light
 if(validObject){
  arr.push(collection[each_object]);
  }   
}
return arr;

}
function whatIsInAName(collection, source) {
  const keyCount = Object.keys(source).length;
  return collection.filter((item) => {
    return Object.entries(item).reduce((acc, [key, value], _, arr) => {
      if (keyCount > arr.length) {
        acc = false;
      } else if (keyCount === arr.length && !source[key]) {
        acc = false;
      } else if (source[key] && source[key] !== value) {
        acc = false;
      }
      return acc;
    }, true)
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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