简体   繁体   中英

Trying to sum an array inside object with for loop

I have a problem and I can't find an answer for that issue, I want to add/sum all values from points in points_sum .

I tried to do this by adding a for loop in the object, but then I get:

'Unexpected token'

How can I do this in the another way?

let sum = 0;
let teams = [
  team1 = {
    name: "Real",
    goal_plus: [3, 4, 2, 1],
    goal_minus: [1, 0, 2, 1],
    points: [3, 3, 3, 1],
    points_sum: for (let i = 0; i < points.length; i++) {
      sum += points[i];
    }
  },
  team2 = {
    name: "Barca",
    goal_plus: [5, 2, 5, 1],
    goal_minus: [1, 0, 0, 1],
    points: [3, 3, 3, 1],
    points_sum: 0
  }
]

You can't add a for loop directly inside an object as a value and also you cannot refer to the object keys or values before it has been created, so even if you could add the for , that part:
i < points.length would thrown an error, something like "points is undefined" , since the object is not created yet and points also doesn't exists in memory.

Another thing, arrays keys can't be named, so keys team1 and team2 will be removed from array, only their value will remain (the objects), if you want to keep those names, make the variable teams an object, not an array.

A solution to your problem can be: create a function that receives an array and makes the sum for you, I'm using inside this function, the .reduce() method.

 let teams = [ { name: "Real", goal_plus: [3, 4, 2, 1], goal_minus: [1, 0, 2, 1], points: [3, 3, 3, 1], points_sum: SumPoints([3, 3, 3, 1]), }, { name: "Barca", goal_plus: [5, 2, 5, 1], goal_minus: [1, 0, 0, 1], points: [3, 3, 3, 1], points_sum: SumPoints([3, 3, 3, 1]) } ] function SumPoints(arr) { return arr.reduce((a, b) => a + b, 0) } console.log(teams)

Another possible way to solve this, if you can't or don't want to pass the whole array as parameter to a external function, is letting points_sum empty and then after creating the array teams , do some job to calculate, using a loop method such as forEach , see in the below snippet:

 let teams = [{ name: "Real", goal_plus: [3, 4, 2, 1], goal_minus: [1, 0, 2, 1], points: [3, 3, 3, 1], points_sum: 0 }, { name: "Barca", goal_plus: [5, 2, 5, 1], goal_minus: [1, 0, 0, 1], points: [3, 3, 3, 1], points_sum: 0 } ] teams.forEach(x => { x.points_sum = x.points.reduce((a, b) => a + b, 0) }) console.log(teams)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM