Search code examples
javascriptfunctionfor-in-loopfor-of-loop

Problem with using for-in/of when returning an object in a function


I just got the result "[object Object]'s score is 0" printed on the terminal. The result 27 was all fine until I separated the function into a return object.

  1. How do I get 27 if I have to return an object?
  2. How do I get "alex" printed on the console.log instead of [object Object]?

const alex = {
  first: [1, 2, 9, 8],
  second: [3],
  third: [0, 0, 0, 1, 3]
};
const gordon = {
  first: [3],
  second: [2, 2, 4, 5, 6, 6, 7, 8]
}

function createPlayer(object) {
  let score = 0;
  return {
    add: function() {
      for (const key in object) {
        for (const item in object[key]) {
          score += object[key][item]
        }
      }
    },
    result: function() {
      return `${object}\'s score is ${score}`
    }
  }
}
createPlayer(alex).add()
console.log(createPlayer(alex).result())


Solution

  • You would not show alex for an object named alex

    You might mean this

    const alex = {
      Name: "Alex",
      first: [1, 2, 9, 8],
      second: [3],
      third: [0, 0, 0, 1, 3]
    };
    const gordon = {
      Name: "Gordon",
      first: [3],
      second: [2, 2, 4, 5, 6, 6, 7, 8]
    }
    
    function createPlayer(object) {
      let score = 0;
      return {
        add: function() {
          for (const key in object) {
            if (key!=="Name") {
              for (const item in object[key]) {
                score += object[key][item]
              }
            }   
          }
        },
        result: function() {
          return `${object.Name}\'s score is ${score}`
        }
      }
    }
    const player1 = createPlayer(alex)
    player1.add()
    console.log(player1.result())