简体   繁体   中英

Getting Key name of an Object item

Before marking this as a duplicate, i've spent a lot of time looking through similar question and most of the answers did not solves my situation.

i have a huge list of items as objects by IDs. like this, in a Map (userDB)

  {
    "15321":{name:"name1",status:"status1"},modules:{...},
    "15322":{name:"name1",status:"status1"},modules:{...},
    "15323":{name:"name1",status:"status1"},modules:{...}
   }

now i need to make an operation in which i need all these IDs, in that case, the key names of every item on it. i need to get these "15321","15322" etc.

more specifically i wanted something that i could fetch in something like

  userDB.forEach( u => {

  //something here to get u's key

  })

i've tried Object.keys(), but it will return a list of IDs as an object

{"15321","15322"...} in which i still cant grab the ID string

i've tried for (i in Object.keys(userDB)) too, no successs

i double-checked for silly syntax errors and everything of the sort.

Things that will be nice to get in mind to answer this:

  • dont try to show me a new way of storing stuff, it is already stored so you will not be of help
  • the result SHOULD be the ID as a string, the name of the key.
  • dont ask "why i want to make this". just answer and dont try to change this scenario. because this is what i've seen in most of the other similar questions and it is what makes me walk in circles every time.

TL;DR. i just want to get the parent key names of the object im currently processing

You might be confused. Object.keys(obj) returns an array. In your case it looks like this: ["15321", "15322", "15323"] . You could iterate through that array like so and you'll have both the key and the object and you'll be able to do with them whatever you want. Below is a for loop that attaches the key to the object as a key named 'key'.

var keys = Object.keys(myObject);

for(var i = 0; i < keys.length; i++){
    var key = keys[i]; // this is your key
    var obj = myObject[key]; // this is the key's value
    obj.key = key;
}

EDIT

In javascript an Array is also an object, but the 'keys' so to speak are usually numbers instead of strings. So an array that looks like this: ["Hello", "there"] is essentially represented like this: { 0 : "Hello", 1 : "there" } When using for-in on an array, it'll loop through the keys, but those keys will be 0, 1, 2... instead of the items themselves.

Object.keys(obj) will return an array. But in your data there is another key modules except IDs. So you can use this :

 var keys = Object.keys(data);
 keys.pop();

 console.log(keys);     // ["15321", "15322", "15323" ...]

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