【问题标题】:Retrieving a string value stored in an array that's stored in a JSON returns only the first character of the string检索存储在 JSON 中的数组中存储的字符串值仅返回字符串的第一个字符
【发布时间】:2018-08-15 22:13:39
【问题描述】:

我这里有这段代码:

const timer = nodeSchedule.scheduleJob("*/5 * * * * *",function() {
    let arr = require("./autometar.json");
    for (let val in arr) {
        console.log(val);
        console.log(val[0]);
    }
});

nodeSchedule 指的是一个名为“node-schedule”的 npm 库;它在这种情况下所做的只是每 5 秒运行一次上面的函数。

autometar.json 是一个文件,当前看起来像这样:

{
    "420431645041229834": [
        "422658075720417290",
        "KSEA",
        "KLAX"
    ],
    "test": [
        "this is a test"
    ]
}

目前,我正在尝试检索存储在autometar.json 中存储的数组中的第一个值。例如,我希望能够从文件中标记为"test" 的数组中检索字符串"this is a test"

但是,当使用给定文件运行上述函数时,控制台会输出以下内容:

420431645041229834
4
test
t

它似乎只返回存储的字符串的第一个字符,但我需要整个字符串。

仅供参考,这是通过 Node.js 运行的。

【问题讨论】:

    标签: javascript arrays json node.js


    【解决方案1】:

    你已经接近了。试试这个:

    console.log(arr[val][0]);
    

    arr 是一个 JSON 对象,val 实际上是键,而不是值。 arr[val] 会给你你想要的数组,然后你可以使用arr[val][0] 得到第一项。

    【讨论】:

      【解决方案2】:

      你可以遍历对象的值,看:

      const sample = {
          "420431645041229834": [
              "422658075720417290",
              "KSEA",
              "KLAX"
          ],
          "test": [
              "this is a test"
          ]
      }
      
      Object.values(sample).forEach(value => {
         const [firstElementOfArray] = value
         console.log(firstElementOfArray)
      })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-19
        • 2017-04-08
        相关资源
        最近更新 更多