How to create an objectBuilder function

Viewed 19

Any help would be appreciated.

Create a function objectBuilder that takes in a number and returns an object whose keys are 0 up to number and the values are that same number multiplied by 5.

2 Answers

Try using for loop

console.log(objectBuilder(5))

// declare function
function objectBuilder(number) {
  // declare empty object
  const obj = {}
  // loop from 0 to number
  for (let i = 0; i <= number; i += 1) {
    // set key of i to value of i * 5
    obj[i] = i * 5
  }
  // return object
  return obj
}

You can do it like this:

I am sorry that I am actually doing this @evolutionxbox

You can create JavaScript class that will do it for you:

class objectBuilder {
    constructor(number){
        for(let i=0;i<=number;++i) this[i]=i*5
    }
}
//to initiate it create new instance of a class
const newObj = new objectBuilder(5)

console.log(newObj)

Related