-1

I have a master object, for example:

MasterObj = { property1: ... method1: ... }

and multiple other objects:

obj1 = { properties and methods... },

obj2 = { properties and methods... }

I need to make each object as a property of the master object, like:

MasterObj.obj1 = obj1; MasterObj.obj2 = obj2;

So that I can use the properties and methods of each little object in this way:

MasterObject.obj1.methodOfObj1(), etc...

and the original properties and methods of the MasterObject.

Is there any efficient way to add each object to the master, without having to do it for each object individually?

Thanks!

7
  • Make a single property with an array of objects. Then you can add them in a loop.
    – Barmar
    Commented Nov 21, 2023 at 20:19
  • 1
    MasterObj.objects = [obj1, obj2, ...]
    – Barmar
    Commented Nov 21, 2023 at 20:20
  • Could you please send me an example? This way I have a property (objects) that will hold an array of objects, but I want to access a property or method of obj1 as MasterObj.obj1.propertyOrmethod. Commented Nov 21, 2023 at 21:21
  • 1
    MasterObj.objects[i].propertyOrMethod.
    – Barmar
    Commented Nov 21, 2023 at 21:22
  • This is really basic data structure use. If you don't know how to use arrays, you need to read a tutorial, I'm not going to try to teach you the basics.
    – Barmar
    Commented Nov 21, 2023 at 21:23

2 Answers 2

0

I'm not sure why you want it, but you can do it by putting all the objects in an array, then loop over the array and use dynamic property names.

let objects = [obj1, obj2, obj3, ...];
objects.forEach((i, obj) => MasterObj['obj' + (i+1)] = obj);
0

Thank you to everyone who answered my question. But, I solved the problem by creating modules for each object and importing via

import * as MasterObj from ...

This way, I got the structure I wanted:

MasterObject.obj1.propertiesAndMethods,
MasterObject.obj2.propertiesAndMethods, and so one...

Thanks!

Not the answer you're looking for? Browse other questions tagged or ask your own question.