如何切换数组的特定属性并使用node.js获取值

li9yvcax  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(223)

我有下面的json文件,数组的长度将始终保持为0。
sample.json:

[
    {
        "session1":"adfuwkko2938893okksjudisojowkekkw",
        "session2":"asfkdkksi2io20909389eolsl0-2889d8",
        "session3":"jfdskdfsoidfosdfi2334234889299209k",
        "session4":"fdsadfkllkpsdiiwkk2388392902019782",
        "session5":"kfksdfuiwllepspoodsfkkllsldlkkmem,",
        "session6":"kdfksdoillsiioepwppeik993289200222"
    }
]

我只想得到上面键的值,它作为函数参数传递,如下所示

const pathToSessionKey = require('../../Sample.json');

async function getValue(keyIn)   // I need to fetch the argument 'key' value from the above json file
{
 return new Promise(function (resolve, reject){
             for(var key in pathToSessionKey[0])
             {
                 if(key === keyIn)   //Checking if the keyIn argument is exist in the json file
                 {
                     console.log(key);  //Able to print the key but not sure how to get value.
                 }
             }
    });
}

例子:
按如下方式运行上述函数:

getValue("session6").then(ele =>{ console.log(ele)});

输出:


**session6**but expected is "kdfksdoillsiioepwppeik993289200222"

有人能帮我找到基于函数参数键的值吗。

ubof19bj

ubof19bj1#

需要改进的两件事
回报承诺
可以使用object.entries在迭代或其他更简单的方法时获取键和值。

async function getValue(keyIn){
 return new Promise(function (resolve, reject){
  for (const [key, value] of Object.entries(pathToSessionKey[0])) {
    if(key === keyIn) {
      console.log(value);
      resolve(value)
    }
  }
  });
}

getValue("session6").then(ele =>{ console.log(ele)}); // kdfksdoillsiioepwppeik993289200222

如果有帮助,请告诉我!!

相关问题