-1

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

polelord
  • 45
  • 6
  • Does this answer your question? [Using variable keys to access values in JavaScript objects](https://stackoverflow.com/questions/922544/using-variable-keys-to-access-values-in-javascript-objects) – juzraai Oct 17 '21 at 14:26
  • If you just need it to log the name Joe, why don't you just do `console.log(search)`? Or did you mean that you need it to log the information associated to the name Joe (`{"nat": "American", "hair": "brown"}`)? – Donald Duck Oct 17 '21 at 15:49

2 Answers2

1

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]);
NickHTTPS
  • 744
  • 4
  • 16
0

Try using names[search] instead

Daniel M
  • 133
  • 3
  • 9