I have an object, like
let foo = {
firstName: 'David',
lastName: 'Divad'
};
I want to get string 'firstName' of foo.firstName
.
I found there is a way to get it but need to hard code the index:
Javascript get Object property Name
I can get 'firstName' by call Object.keys(foo)[0] But I don't want to hard code the index because if the index was changed, I could not detect error in code at the compile, validation time. So I need to get string field name from field foo.firstName.
I wonder if there is a function such as getFieldName below do to that. For example :
let foo = {
firstName: 'David',
lastName: 'Divad'
};
console.log(getFieldName(foo.firstName)); // expect print out 'firstName'
or
console.log(getFieldName(foo, foo.firstName)); // expect print out 'firstName'
Is there any way to get field name of a javaScript object with object's field as parameter? Can anyone give me an idea?