简体   繁体   中英

Getting an object by its name contained in a string

I am trying to get a const object indirectly by its name, which is contained in a string. I have no idea if this is possible but if it is, it would make my life a hell of a lot easier. As an example in pseudocode: var obj = findObject("myConstObject"); I know this is a strange thing to need, but I am dealing with quite a large amount of data, and being able to grab objects in this way would work a lot better with my existing code. Thanks in advance!

You can use Object.getOwnPropertyNames() to get all property names of an object. Here is an example that demonstrates how to search a myObj1 that is in the global window scope, and a myObj2 that is in the myStuff object scope:

 // object attached to window object: myObj1 = { a: 1 }; function getKeyNames(aThis) { return Object.getOwnPropertyNames(aThis || globalThis).sort(); } console.log('search myObj1 in global scope:', getKeyNames().filter(name => name === 'myObj1')); // object attached to my on stuff: const myStuff = { myObj2: { b: 2 }, deeperLevel: { myObj3: { b: 3 }, } } console.log('search myObj2 in myStuff scope:', getKeyNames(myStuff).filter(name => name === 'myObj2'));

Output:

search myObj1 in global scope: [
  "myObj1"
]
search myObj2 in myStuff scope: [
  "myObj2"
]

Notes:

  • if needed, expand this code to search recursively the object hierarchy, so that myStuff.deeperLevel.myObj3 can be found searching myStuff
  • if needed, expand this code to search a list of objects of interest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM