[英]Printing array elements one by one instead of printing array
我有 .json 文件,但由於它很大,我將粘貼一個示例來說明它的樣子:
[{"translations": {
"ces": {
"official": "Aruba",
"common": "Aruba"
},
"deu": {
"official": "Aruba",
"common": "Aruba"
},
"est": {
"official": "Aruba",
"common": "Aruba"
},
"fin": {
"official": "Aruba",
"common": "Aruba"
},
"fra": {
"official": "Aruba",
"common": "Aruba"
},
"hrv": {
"official": "Aruba",
"common": "Aruba"
},
"hun": {
"official": "Aruba",
"common": "Aruba"
},
"ita": {
"official": "Aruba",
"common": "Aruba"
},
"jpn": {
"official": "\u30a2\u30eb\u30d0",
"common": "\u30a2\u30eb\u30d0"
}}]
原來的.json文件包含了10多個這樣的塊。 好奇的話可以查看鏈接: https://raw.githubusercontent.com/TheRadioDept/technical-question/main/countries.json
我還有 javascript 代碼,它使用require
方法從 this.json 文件中讀取值。
const enteredKey = process.argv.slice(2);
console.log('Key is : ', enteredKey);
/* Checking if number of parameters more than 0 */
/* Checking if entered translation key is supported by.json file. */
// eslint-disable-next-line max-len
if (enteredKey.length < 2 && enteredKey !== null && removeDuplicates(keys).includes(enteredKey[0])) {
try {
console.log(data.map(point => point.translations[0][enteredKey] ?
// eslint-disable-next-line max-len
point.translations[enteredKey].official: `No translation for ${ enteredKey }.`));
} catch (error) {
console.log('Cannot translate variable');
}
} else {
console.log('Incorrect key parameter');
}
當程序運行時,它接受一個 CLI 參數,例如deu
,並返回 .json 文件中此密鑰的所有參數(正式名稱)。 請注意,在我的本地 PC 上,.json 和 JS 文件都存儲在同一個文件夾中。
我需要的不是為整個keys
數組做一個 console.log 而是一個一個地記錄(打印)它們。 我試過使用for loop
,但由於我不熟悉 .json 結構,我不知道如何讓它單獨打印。 這是我試過for loop
:
for(i = 0; i < data.translations[enteredKey]; ++i) {
console.log(data.map(point => point.translations[enteredKey] ?
// eslint-disable-next-line max-len
point.translations[enteredKey].official: `No translation for ${ enteredKey }.`));
}
output 是console.log('Cannot translate variable');
.
有人可以幫忙嗎?
如果我正確理解您的要求,您想要檢查您擁有的 JSON 中的 enteredKey,如果密鑰可用,您想要打印official key value
,否則No translation available
文本。 如果是,那么你可以試試這個:
const data = [{ "translations": { "ces": { "official": "Aruba", "common": "Aruba" }, "deu": { "official": "Aruba", "common": "Aruba" }, "est": { "official": "Aruba", "common": "Aruba" } } }]; const enteredKey = 'deu'; const res = data.map(point => point.translations[enteredKey]? point.translations[enteredKey].official: `No translation for ${enteredKey }.`)[0]; console.log(res);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.