【问题标题】:Try to get key values recursively from JSON in Angular 5尝试从 Angular 5 中的 JSON 递归获取键值
【发布时间】:2018-11-03 21:36:59
【问题描述】:

我想从 JSON 文件中检索 所有 键值。例如:

{
 "total_count": 6,
 "incomplete_results": false,
 "items": [
  {
    "url": "https://api.github.com/repos/Samhot/GenIHM/issues/6",
    "id": 293237635,
    "number": 6,
    "title": "Rechercher des documents",
    "user": {
      "login": "Samhot",
      "id": 7148311
 ]
}

我想得到:
["total_count", "incomplete_results", "items", "url", "url", "number", "title", "user", "login", "id"]

我有一个函数可以在 observable 中返回我的 JSON 内容:

  getConfig(): Observable<any> {
    return this.http.get<any>(this.myURL);
  }

之后,使用.map 重新格式化数据以仅使用Object.keys() 函数获取键:

  merge()
  .pipe(
    startWith({}),
    switchMap(() => {
      return this.getConfig();
    }),
    map(data => {
      return Object.keys(data.items[0]);
      }
    )
  )
  .subscribe(data => {
    this.dispo = data;
  });

我的问题是我只得到了我告诉的 JSON 级别的键 (data.items[0]) 而不是祖先或后代。

当然我可以创建多个请求,但它要求提前知道 JSON 的结构,我想要的是使其通用 ...

无论 JSON 的结构如何,我如何才能拥有一个包含所有键的数组?

提前致谢!

【问题讨论】:

    标签: json typescript key angular5


    【解决方案1】:

    你需要做一个递归函数,比如:

    function getDeepKeys(obj) {
      
        const keys = Object.keys(obj);
    
      const childKeys = keys
        .map(key => obj[key])
        .map(
          value =>
            Array.isArray(value)
              ? getDeepKeys(value[0])
              : typeof value === "object"
                ? getDeepKeys(value)
                : []
        )
        .reduce((acc, keys) => [...acc, ...keys], []);
      return [...keys, ...childKeys];
    }
    
    const obj = {
      total_count: 6,
      incomplete_results: false,
      items: [
        {
          url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
          id: 293237635,
          number: 6,
          title: "Rechercher des documents",
          user: {
            login: "Samhot",
            id: 7148311
          }
        },
        {
          url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
          id: 293237635,
          number: 6,
          title: "Rechercher des documents",
          user: {
            login: "Samhot",
            id: 7148311
          }
        }
      ]
    };
    
    console.log(getDeepKeys(obj));

    然后你会使用map(getDeepKeys)。请注意,此函数假定数组中的所有项目都具有相同的架构。

    【讨论】:

    • 谢谢 J. Pichardo,但您的解决方案没有返回“用户”键...["total_count", "incomplete_results", "items", "url", "number", "title", "user"] 如果我想要所有键,我必须添加 ...Object.keys(data.items[0].user),但这不是通用的,它只适用于这个 JSON
    • @samhot 抱歉,我完全错过了示例中的这些属性,我已经更新了问题。
    • 再次感谢您,但这次它只返回“用户”中的密钥(["login", "id"])...我想如果我们可以更改return [...Object.keys(obj), ...childKeys]; 以添加“parentKeys”它不会?
    • 嗯,是的,我这样做是作为一个快速实验,但我确实有一个运行的例子。我会尽快发布的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2012-01-02
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多