Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138134

Get field name of a javascript object with object's field as parameter [duplicate]

$
0
0

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

Background: I don't want to hard code 'firstName' or index because if the field name or It's index was changed, I could not detect error in code at the compile, validation time. So I need to get string file name from 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));  // print out 'firstName'

or

console.log(getFieldName(foo, foo.firstName));  // 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?


Viewing all articles
Browse latest Browse all 138134

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>