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 calling Object.keys(foo)[0]. 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 time. With object's field variable we always can detect issue first at the compile time not runtime as other ways.
I need to get string field name from field foo.firstName not by hard code the index or string but object's field variable (ex: 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 variable as parameter?