【问题标题】:make json array as new array for category and subcategory将 json 数组作为类别和子类别的新数组
【发布时间】:2018-08-23 02:57:46
【问题描述】:

我正在处理 django rest 和 angular 这个 json 数组来自服务器 ic 包含类别和子类别值.. 我正在尝试构建一个动态导航栏,所以我想像这样排列这些数据 [ [web development] : ["subCat1","subcat2",....] [android development] : ["subCat1","subcat2",....] ] 访问类别及其相关子类别

我尝试过这样的事情:但它只设置键和值是空的

  public categories = [[], [], [], []];
  public data;
      for (let i = 0; i < this.data.length; i++) {


        if (this.data[i].cat_id != null) {
          this.categories[i][this.data[i].title] = [];


        }
        if (this.data[i].parent_id != null && this.data[i].parent_id == this.data[i].cat_id) {
          this.categories[i][this.data[i].title] = [this.data[i].title]
        }


      }

它的服务器响应

  [
        {
            "id": 5,
            "cat_id": 0,
            "parent_id": null,
            "title": "web development"
        },
        {
            "id": 6,
            "cat_id": 1,
            "parent_id": null,
            "title": "android development"
        },
        {
            "id": 7,
            "cat_id": null,
            "parent_id": 0,
            "title": "php"
        },
        {
            "id": 8,
            "cat_id": null,
            "parent_id": 1,
            "title": "java"
        }
    ]

【问题讨论】:

标签: javascript json typescript django-rest-framework


【解决方案1】:

这里有一些代码可以满足你的需求:

interface Categories {
    [title: string]: string[]
}

let categories: Categories = {};

data.filter(c => c.parent_id === null).map(c => <{ title: string; subcategories: string[] }>{
    title: c.title,
    subcategories: data.filter(sc => sc.parent_id === c.cat_id).map(sc => sc.title)
}).forEach(c => {
    categories[c.title] = c.subcategories;
});

console.log(categories);

如您所见,我定义了一个接口。然后我创建一个包含标题及其子类别的对象的时间数组。之后,我将该结构展平,将其变成您需要的结构。

输出是:

{
    "web development": ["php"],
    "android development": ["java"]
}

【讨论】:

    【解决方案2】:

    我不知道我是否理解正确。 我假设“数据”变量包含 JSON,并且预期的输出是:

    {
        "web development": ["php"],
        "android development": ["java"]
    }
    

    这可以通过首先创建一个“类别”对象来实现,该对象将用于获取给定“parent_id”的“标题”。

    const categories = data.reduce((acc, d) => {
        if (d.parent_id === null) {
            acc[d.cat_id] = d.title
        }
    
        return acc;
    }, {});
    

    然后用

    创建结构
    const structure = {};
    
    data.forEach((d) => {
        if (d.parent_id === null) {
            structure[d.title] = [];
        } else {
            structure[categories[d.parent_id]].push(d.title);
        }
    });
    

    结构现在包含我之前描述的数据。

    【讨论】:

      猜你喜欢
      • 2018-08-23
      • 2022-09-30
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多