0

I need to dynamically extract the key value of a JSON file and use it as a parameter in a function later. In the example below, I want to derive the first key from the JSON (firstname) and then use that to get "Bob" to return. The snippet below contains the rough idea of what works and what doesn't. I won't know that firstname is the key value until the json file has already been generated so I would really like to get the last line to work.

Even though the console logs "firstname" for my variable fName, when I use fName later it returns undefined.

var person = [];
person = [{'firstname' : 'John', 'lastname': 'Doe'},{'firstname': 'Bob', 'lastname': 'Smith'}]

var kPeeps = Object.keys(person[1]);
var fName = kPeeps[0];

console.log(kPeeps); // Keys of person - returns firstname, lastname
console.log(fName); // Item 1 in the array of Keys - returns firstname

console.log(person[1].firstname); //Works - Returns Bob
console.log(person[1].fName); //Not so much - Returns Undefined
Paul S
  • 3
  • 1
  • because it is looking for "fName" not the variable.... dot notation can not use variables. You would have to use bracket notation, but you most likely should be using Object.entries() – epascarello Nov 15 '19 at 21:05
  • to lookup a variable key you need the square bracket notation: `person[1][fName]` – Robin Zigmond Nov 15 '19 at 21:10
  • Question title has little to do with the problem, which is more along the lines of "how do I access a property by a variable key" - `person[1].fName` accesses the literal key `"fName"`, not the value stored in the variable fName. Use bracket accessors for variable key names, e.g. `person[1][fName]` - see [this MDN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) for more – Klaycon Nov 15 '19 at 21:12
  • You can use a simple parameterized function like:::: const person = [{'firstname' : 'John', 'lastname': 'Doe'},{'firstname': 'Bob', 'lastname': 'Smith'}]; function getFirstName(index, prop) { return person[index][prop]; } console.log(getFirstName(1, 'firstname')); – Rajesh Dwivedi Nov 15 '19 at 21:21

2 Answers2

0

if you need a simple and quick solution, you need to change person[1].fName to person[1][fName]

var person = [];
person = [{'firstname' : 'John', 'lastname': 'Doe'},{'firstname': 'Bob', 'lastname': 'Smith'}]
var kPeeps = Object.keys(person[1]);
var fName = kPeeps[0];

console.log(kPeeps); // Keys of person - returns firstname, lastname
console.log(fName); // Item 1 in the array of Keys - returns firstname

console.log(person[1].firstname); //Works - Returns Bob
console.log(person[1][fName]); //Now it should return Bob
0

you can use this as below person[1][fName]