Reputation: 75
I have been looking at this and reading for a while but can't seem to understand. I am sure it is simple but I can not figure out why I can access the data in collection. I get an error of
test undefined
If I move outside of the for loop I can access it just fine. I am obviously missing something simple. Any help would be great.
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change ode below this line
var test = Object.values(source);
for(var i = 0; i < collection.length; i++) {
if (collection[i].test === source[0].test){
arr[i] = collection[i];
}
}
// Only change code above this line
//arr = collection[0].last;
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio",
last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
Upvotes: 0
Views: 84
Reputation: 109
try this.
function whatIsInAName(collection, source) {
var arr = [];
var keys = Object.keys(source);
for(var i = 0; i < collection.length; i++) {
var item = collection[i];
var all = true;
for(var k = 0; k < keys.length; k++){
var key = keys[k];
if(item[key] != source[key]){
all = false;
break;
}
}
if(all){
arr.push(item)
}
}
return arr;
}
Upvotes: 0
Reputation: 747
The objects you're passing in have no key named test
. If you're trying to use the variable you created here var test = Object.values(source);
, this won't work because test
is an array anyways.
You could try something like:
if (collection[i][test] === source[0][test])
but I don't think that will work either because test
should have the value of Capulet
according to documentation for Object.values()
Upvotes: 0
Reputation: 2107
In your code Object.values returning the value of source that is "Capulet", whereas in for loop you are equating source as an array(source is object), that is why, test is undefined
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change ode below this line
var test = Object.keys(source);//changes values to keys
console.log(test);
for(var i = 0; i < collection.length; i++) {
if (collection[i][test] === source[test]){ //change how you are accessing test
arr.push(collection[i]);
}
}
// Only change code above this line
//arr = collection[0].last;
console.log(arr);
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio",
last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
Upvotes: 1