user1464139
user1464139

Reputation:

How does Object.keys work when applied to a Javascript variable?

I have some code in my application like this:

   var msg = data.data.modelState[Object.keys(data.data.modelState)[0]];

Can someone please explain what the Object.keys part of this code is doing and give me some idea what the data.datamodelState object looks like.

Right now it is my understanding that this code is not working but the code around it is not so I can't debug to find out.

Upvotes: 1

Views: 62

Answers (1)

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

Object.keys() returns array of keys of that object. In your code, you are accessing first element of array. i.e. first key of data.data.modelState.

This code is just to get the value of first key of data.data.modelState.

For Example

Suppose

 data.data.modelState={tmpkey:"Some Value"}
 var msg = data.data.modelState[Object.keys(data.data.modelState)[0]];
 console.log(Object.keys(data.data.modelState)[0]); //will Print ["tmpkey"]
 console.log(msg); //It will print "Some Value";

You can access any key of object using []; And here you are accessing first key.

var msg = data.data.modelState[Object.keys(data.data.modelState)[0]];

This will become

var msg = data.data.modelState[["tmpkey"][0]];

And it will become

var msg = data.data.modelState["tmpkey"]; //Simply it will return value of tmpKey property.

Upvotes: 1

Related Questions