将子类别作为数组对象中的数组

时间:2018-03-15 04:57:55

标签: javascript json typescript django-rest-framework

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

结果应该是这样的:

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

mycode的:

  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"
        }
    ]

1 个答案:

答案 0 :(得分:2)

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

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