foxDev
foxDev

Reputation: 87

How can I create a function that check boolean field in array of object javascript

The final goal: if all the field are true the last object.field must change to true

const badges = [

  { name: "peter", given : true, points: 10 },
    { name: "Alice", given : true,  points: 100 },
    { name: "Hugo", given: true,  points: 100 },
    { name: "Salah", given: false,  points: 500 },
    { name: "Rui", given: false, points: 1000 },
    { name: "Jimena", given: false,  points: 10000 }

]

My code:

const badges = [
    { name: "peter", given : true, points: 10 },
    { name: "Alice", given : true,  points: 100 },
    { name: "Hugo", given: true,  points: 100 },
    { name: "Salah", given: false,  points: 500 },
    { name: "Rui", given: false, points: 1000 },
    { name: "Jimena", given: false,  points: 10000 }
]

let count = 0
badges.forEach((ele, index) => {
  const l = badges.length
  ele.given === true ? count = count + 1 : count
  count == l - 1 ? badges[l - 1].given = true : badges[l - 1].given
})

console.log(badges)

What I would like to achieve: is a more generic function that can works anywhere but I could not find the way or maybe a simplest way.

Upvotes: 0

Views: 248

Answers (1)

Jamiec
Jamiec

Reputation: 136239

This will work so long as the field provided is a boolean. Makes use of slice to get everything but the last element and every to check all those conform to a condition.

const badges = [

  { name: "peter", given : true, points: 10 },
    { name: "Alice", given : true,  points: 100 },
    { name: "Hugo", given: true,  points: 100 },
    { name: "Salah", given: true,  points: 500 },
    { name: "Rui", given: true, points: 1000 },
    { name: "Jimena", given: false,  points: 10000 }

]

function check(input, field) {
  var result = input.slice(0,input.length-1).every(x => x[field]);
  if(result) {
    badges[input.length-1][field] = true;
  }
}

check(badges,"given");
console.log(badges)

Upvotes: 4

Related Questions