0

I have this code, I'm interested in whether it is possible to get the name of the passed object inside the useConf function, namely "container__wrapper", and not "Object".

const conf = {
    container__wrapper : {
        style : {
            width : '100%'
        }
    } as Component,

    toolbar : {
        ui: "default"
    } as Component,
};

const useConf = (config: Object) => {
    return config.constructor.name; // Return "Object"
}

console.log(
    useConf(conf.container__wrapper);
);
  • 1
    Are you trying to get the name of the key or the value? If you want the key specifically 'container__wrapper', use `Object.keys()` – dale landry Jan 31 '22 at 17:28
  • You can't, unless you're going to assign a name property to that object. JavaScript objects don't have a name nor a parent, all the objects are anonymous, and object properties (or variables) are only containing a reference to an object, they don't "own" the object they're referring to. – Teemu Jan 31 '22 at 17:35
  • @Teemu great answer with explain, thanks. – dakovic323 Jan 31 '22 at 17:40
  • But, you can figure this out given your code sample. If you have access to your `conf` parent object from within the `useConf` function (it appears that you do), then you can check the `config` parameter for equality with the properties of conf. Would be nice if I could add this as an answer :), but its closed. ``` const useConf = (config: Object) => { let confName = null; Object.values(conf).some([key, value]) => { if (value === config) { confName = key; return true; } }}); return confName; } ``` – Ben Taber Jan 31 '22 at 17:40

2 Answers2

0

You can't, but you can add a name property to your object for this purpose, e.g:

const conf = {
    container__wrapper : {
        name: 'container__wrapper',
        style : {
            width : '100%'
        }
    } as Component,

    toolbar : {
        name: 'toolbar',
        ui: "default"
    } as Component,
};

const useConf = (config: Object) => {
    return config.name; // Returns "container__wrapper"
}

console.log(
    useConf(conf.container__wrapper);
);
Xavier B.
  • 533
  • 2
  • 9
0

Like this:

const useConf = (config: Object) => {
    return Object.keys(config)[0] // Return "first key name"
}
Konflex
  • 465
  • 3
  • 11