尝试从Angular 5中的JSON递归获取键值

时间:2018-05-24 15:27:28

标签: json typescript key angular5

我想从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的结构如何,如何拥有包含所有键的数组?

提前致谢!

1 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
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));
&#13;
&#13;
&#13;

然后你会像map(getDeepKeys)那样使用。请注意,此函数假定数组中的所有项都具有相同的模式。