Im trying to figure out how can I tell javascript to filter array of objects, here's the code
I hope that I explained everything in code the //* is where the problem is.
function whatIsInAName(collection, source) { // first arg is the array of objects, second arg is the object i want to get matched
let arr = [];
let newArr = Object.getOwnPropertyNames(source); // this converts the object into an array
for (let i = 0; i < collection.length; i++) { // loop through objects
for (let s = 0; s < newArr.length; s++) { // loop through array
if (collection[i].hasOwnProperty(newArr[s]) === true) { //* it returns an object if it matches 1 element of array
console.log(collection[i]) // i want it to return only if all elements on the array matches
arr.push(collection[i]);
}
}
}
return arr;
}
whatIsInAName([{
"apple": 1,
"cookie": 6
}, {
"apple": 1,
"bat": 2
}, {
"cookie": 2
}, {
"apple": 1,
"cookie": 4
}, {
"apple": 1,
"bat": 2,
"cookie": 2
}], {
'apple': 1,
"cookie": 2
})
arr.every(e => *condition*)will returntrueif every element of array matches the condition.if(collection[i].hasOwnProperty(newArr[s]) === true)here i wanted to check if all the elements on the array matches the object properies and return that object, instead the if statement returns every object that matches 1 array element or more{ "cookie": 2 }to log on output you can see that source has 2 properties{ 'apple': 1, "cookie": 2 }