0

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.

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

4 Comments

I am trying to understand better your code, please can you tell me if x[field] and x.fieldis the same in this case? and why when I do a console.log(badges[input.length-1][field]) inside a function it's have a different value from doing it out side?thanks
Yes x.field and x["field"] are the same, although the latter allows you to reference the field using a string (see "square bracket notation"). Your second question is unclear. Do you mean before or after calling check in this example? That method is updating a value
you mean badges[index][field]? if I use it out side the function scope it's not working, I m just trying to understand the code to use it in another function in the future, do you have any link to information to understand better how to use iteration in array of objects?.@jamiec

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.