Home > database >  How to create an objectBuilder function
How to create an objectBuilder function

Time:08-24

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.

CodePudding user response:

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
}

CodePudding user response:

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