2

Let's say I have an array of defined classes

class Dick { };
class Duck { };
class Dear { };

const arr = [Dick, Duck, Dear];

And I also have an object

const obj = {};

And I wanted to define a function that would take that object and that array and apply some magic then return a new object like this. In this example, this new created object has properties like the class names above (and the first letter of each became lowercase) and every single property have a value of the instance of that class. Is it possible to do in JavaScript?

obj = magicFunction(obj, arr);


console.log(obj)
/*
{
 dick: <instance of the class Dick>,
 duck: <instance of the class Duck>,
 dear: <instance of the class Dear>
 ...
}
*/

NOTE:

<instance of the class ... > is NOT a string, it's a real instance.

2 Answers 2

3

Perhaps this is what you are looking for?

class Dick { };
class Duck { };
class Dear { };

const dict = { Dick, Duck, Dear };
function magicFunction(obj={}, classes) {
  let results = {};
  for (let key in classes) {
    results[key.toLowerCase()] = new classes[key](obj)
  }
  return results;
}

let obj = {};
obj = magicFunction(obj, dict);
console.log(obj);

Changed the arr to a dictionary using destructuring to preserve the class names.

The original obj is passed in to each class's constructor; allowing you to initialize all of them with the same values, all at once!

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

Comments

1

You can get class name by using instance.constructor.name and combine that with reduce method to return the desired result.

class Dick {};
class Duck {};
class Dear {};

const arr = [Dick, Duck, Dear];

const obj = arr.reduce((r, Cls) => {
  const inst = new Cls();
  const key = inst.constructor.name.toLowerCase()
  r[key] = inst;
  return r;
}, {})

console.log(obj)

Comments

Your Answer

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