1

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.

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

4 Comments

This is happening because the modelState doesn't have numeric keys, but probably some string keys which are not known before..
so then modelState would be containing multiple objects with a string key and probably a string variable?
@Anne, here you are accessing first key only. Object.keys(data.data.modelState)[0] will return you first key only.
@Anne, This method is good only if you dont know what keys are in object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.