我正在尝试解决 freeCodeCamp运动并卡住了。练习的目标是:创建一个函数,它遍历对象数组(第一个参数)并返回具有匹配属性和值对的所有对象的数组(第二个参数)。如果要包含在返回的数组中,源对象的每个属性和值对都必须存在于集合中的对象中。
所以我所做的是制作一个集合的键对数组,以及另一个包含源键对的数组。我嵌套了 for 循环以找到匹配的键,如果找到了这些键,则比较属性。
但不知何故,我的代码没有返回任何匹配项。
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");
}
}
}
}
谁能指出我做错了什么?
我还创建了一个 JSfiddle如果你想修补。
最佳答案
当我偶然发现一些资源可以提供帮助时,我也被困在这个问题上了一个小时。
我发现我可以使用内置的循环方法来大大简化我的代码,而不是困惑的嵌套 for 循环。
这是我找到我的解释的地方:
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;
}
关于javascript - 在对象数组中搜索匹配的属性和值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34899684/