I am getting a false Boolean when each object does have name as a property. I consoled the prop var and got 0 back. What am I doing wrong and why is it not looping over every object.
function truthCheck(collection, pre) {
for (let prop in collection) {
console.log(prop)
if (collection[prop].hasOwnProperty(pre) && Boolean(collection.forEach((item) => item[pre]))) {
return true
} else return false
}
}
console.log(truthCheck([{
name: "Quincy",
role: "Founder",
isBot: false
}, {
name: "Naomi",
role: "",
isBot: false
}, {
name: "Camperbot",
role: "Bot",
isBot: true
}], "name"))
You are returning a boolean so the loop never gets past the first iteration. Use Array.some or Array.every to check multiple items and return from within that context.
Also use a for of loop to have easier access to items.
I am not sure exactly what logic you want with the inner forEach boolean test, so I removed it and just tested for property defined. This snippet should set you in the right direction, but add to that logic if you want to test for empty string, etc.
Finally, I added an allPassed value that is now returned from the function so you can track if any items failed.
function truthCheck(collection, pre) {
let allPassed = true
for (let item of collection) {
console.log(item)
if (item.hasOwnProperty(pre)) {
console.log(true)
} else {
console.log(false)
allPassed = false
}
}
return allPassed
}
console.log(truthCheck([{
name: "Quincy",
role: "Founder",
isBot: false
}, {
name: "Naomi",
role: "",
isBot: false
}, {
name: "Camperbot",
role: "Bot",
isBot: true
},
{
role: "No Name",
isBot: true
}], "name"))
why is it not looping over every object?
Because return stops the execution of the function. You have a return in both branches (if and else) so you end the function after the first element in collection.
What am I doing wrong?
The return from above and you're looping over all elements in the collection (in the worst case) "twice" (actually it's collection.length * collection.length times). Once with for...in and once with collection.every().
To determine if all elements in collection have a specific property, and if that property has a truthy value you only need a slightly modified version of the if condition:
collection.every(item => item.hasOwnProperty(pre) && item[pre])
function truthCheck(collection, pre) {
return collection.every(item => item.hasOwnProperty(pre) && item[pre]);
}
const input = [
{ name: "Quincy", role: "Founder", isBot: false },
{ name: "Naomi", role: "", isBot: false },
{ name: "Camperbot", role: "Bot", isBot: true }
];
const result = truthCheck(input, "name");
console.log(result);
Here's my version of code:
let istruthCheck = (arr, pre) => {
return arr.every( item => item.hasOwnProperty(pre) )
}
const arr = [
{name: "Quincy", role: "Founder", isBot: false},
{name: "Naomi", role: "", isBot: false},
{name: "Camperbot", role: "Bot", isBot: true}
];
console.log( istruthCheck(arr, "name") )
Hope it helps... :)