Home > Software design >  How can I return a parameter of .Json file based on the User's input in Javascript program?
How can I return a parameter of .Json file based on the User's input in Javascript program?

Time:03-26

I have a problem with printing the value from .json file. Based on the user's input, program should access .json file and return parameter same as input. But when I run the code it returns undefined. I tried using toLowerCase, but that didn't work for me. Is it possible to extract the same value as a user input from .json file?

GitHub link for more context and .json file itself: https://github.com/TheRadioDept/technical-question

const data = require('/home/user/progs/JS/countries.json'); /* Passing a .json file into javascript*/

var keys = ['cym','deu','fra','hrv','ita','jpn','nld','por','rus','spa'];  /* creating an array of translation keys */
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});


rl.question('Please enter the translation key ', (key) => {
    if (keys1.includes(key)){
        console.log(data.map(point=>point.translations.key));
    }
else {
    console.log("Translation key is not supported in this program. ");
}
rl.close();
});

CodePudding user response:

Try using

data.map(point=>point.translations[key])

When you use .key, Javascript looks for a key prop inside data.translations but you want to look for dynamic value of key which could be parsed using above format.

  • Related