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
4
  • 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() Commented Nov 15, 2019 at 21:05
  • to lookup a variable key you need the square bracket notation: person[1][fName] Commented Nov 15, 2019 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 for more Commented Nov 15, 2019 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')); Commented Nov 15, 2019 at 21:21

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.