The following script is an example script. I need it to log the name Joe;
const names = `
{
"Joe": {
"nat": "American",
"hair": "brown"
},
"Peter": {
"nat": "German",
"hair": "blond"
}
}
`;
const load = JSON.parse(names);
var search = "Joe"
console.log(names.search);
The last line outputs "undefined" because it's searching for "search" instead of the value of the variable search. Before you ask: yes, I need it to be a variable (because the value of the variable would actually be the value of an input). Is there any way I can search the value of a variable in the JSON bit?
Thanks in advance
CodePudding user response:
Almost there (you still have to parse it first):
const names = `
{
"Joe": {
"nat": "American",
"hair": "brown"
},
"Peter": {
"nat": "German",
"hair": "blond"
}
}
`;
const load = JSON.parse(names);
var search = "Joe"
console.log(load[search]);
CodePudding user response:
Try using names[search] instead