【问题标题】:JSON ForEach in Node.JS [duplicate]Node.JS 中的 JSON ForEach [重复]
【发布时间】:2025-12-02 09:00:01
【问题描述】:

我使用 Node.JS 编写了一个 url-shortener 并保存在 json-data 中。现在我正在为我的团队编写一个 Web 仪表板来管理网址。我喜欢使用forEach,因为我可以轻松地使用它为每个条目添加代码到我的html 站点。我的问题: 我有这样的json数据:


    {
      "support": {
        "url": "https://this-is-the-url.end",
        "author": "Name of the Author"
      },
      "invite": {

      "url": "https://an-other-url.end",
      "author": "Name of the Author"
    },
    .
    .
    .
    }

我不知道如何拆分它,所以我可以使用

Object.forEach(json => {
var author = json.author
var url = json.url

*add code to html code*

})

我已经在 * 上搜索过,但找不到任何东西。 有人可以帮我吗?

【问题讨论】:

  • forEach 适用于数组。如果它不是数组,则不能使用 forEach。请展示更多作者的更好示例。向我们展示您现在拥有的一些……
  • 还有作者和support.author。你想要哪一个
  • 哦,我在输入 json 数据时出错了。现在应该会更好
  • 不是更好,如果是数组请举例3组数据

标签: javascript json foreach


【解决方案1】:

像这样?

Object.keys(bigJson).forEach(key => {
  const json = bigJson[key];
  const author = json.author;
});

(请注意,bigJsonjson 不是实际的 JSON 字符串,它们是对象,但我想保留 OP 的命名以避免在这一点上造成混淆。)

【讨论】:

  • 我稍后再试。如果它为每个键运行可能是我的问题...
【解决方案2】:

可能是这样的:

import json from '/some/path/to/urls.json';

Object.entries(([key, value]) => {
  doSthWith(key); // 'support', 'invite';
  doSthElseWith(value.url, value.author);
})

【讨论】: