【问题标题】:Make subcategory as array in object of array将子类别作为数组对象中的数组
【发布时间】:2018-08-23 19:37:17
【问题描述】:

我正在研究 django rest 和 angular。此 json 数组来自服务器,包含类别和子类别值。 我的代码将在数组的单独键中创建类别和相关子类别。但我想将子类别保留为同一对象中的对象中的数组。

结果应该是这样的:

[{"title":"title of category","sub":[array of related sub]} , ...]

我的代码:

  public data = SERVERRESPONE;
  public categories = [];

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

服务器响应:

[
        {
            "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】:

    这是一个很好的问题,但它的解决方案非常简单!

    const array = [
        {
            "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"
        }
    ]
    
    let result = []
    
    
    for (let key of array) {
    
        if (key.parent_id === null) {
            let new_key = key,
                sub = []
    
            for (let iterator of array) 
                if (iterator.parent_id === key.cat_id)
                    sub.push(iterator)
    
            new_key.sub = sub
            result.push(new_key)
        }
    
    }
    
    console.log(result)

    【讨论】:

      猜你喜欢
      • 2018-08-23
      • 1970-01-01
      • 2023-03-12
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多