【发布时间】: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