[英]How to create a new Data Structure from incoming JSON based on specific child Nodes
I have an incoming Json list that looks like the below我有一个传入的 Json 列表,如下所示
[{
"id": 190,
"title": "This is a Story title",
"category": [{
"id": 43,
"title": "XXX",
"titleFr": "YYY"
}, {
"id": 27,
"title": "AAA",
"titleFr": "BBB"
}]
}, {
"id": 191,
"title": "This is a Story title 2",
"category": [{
"id": 43,
"title": "XXX",
"titleFr": "YYY"
}]
}]
I would like to be able to find all the Unique Category Ids, then create a new Data Structure (array) by Grouping by the Category...ie我希望能够找到所有唯一的类别 ID,然后通过按类别分组来创建一个新的数据结构(数组)...即
Category 27- AAA类别 27- AAA
This is a Story title这是一个故事标题
Category 43 - XXX类别 43 - XXX
This is a Story title这是一个故事标题
This is a Story title 2这是一个故事标题 2
I have the below code, which I can use so far to traverse and get the Categories我有以下代码,到目前为止我可以使用它来遍历并获取类别
$.each(data, function (i, ob) {
$.each(ob, function (ind, obj) {
if (ind === "category") {
Categories.push(this);
}
});
});
console.log(Categories);
I feel like the above would be highly inefficient, plus it doesn't account for if the Category already exists.我觉得上面的方法效率很低,而且它不考虑类别是否已经存在。
Secondly, I think I would then need to go back over the entire list again, look for the Category.Id, create a new obj when found, then add to a new list?其次,我想我需要再次返回整个列表,查找 Category.Id,找到后创建一个新的 obj,然后添加到新列表中?
I feel like there's a lot of looping here and using $.each would be very inefficient.我觉得这里有很多循环,使用 $.each 会非常低效。
Any help would be appreciated.任何帮助,将不胜感激。
You can achieve this with vanilla JavaScript, building a list of categories using Array.reduce
on your input data, iterating over each of the categories for each story and pushing the story titles into an array in the category entry.您可以使用 vanilla JavaScript 实现这一点,在输入数据上使用
Array.reduce
构建类别列表,迭代每个故事的每个类别并将故事标题推送到类别条目中的数组中。 You can then use Object.values
to convert the result object into an array:然后,您可以使用
Object.values
将结果对象转换为数组:
const data = [{ "id": 190, "title": "This is a Story title", "category": [{ "id": 43, "title": "XXX", "titleFr": "YYY" }, { "id": 27, "title": "AAA", "titleFr": "BBB" }] }, { "id": 191, "title": "This is a Story title 2", "category": [{ "id": 43, "title": "XXX", "titleFr": "YYY" }] }]; const categories = Object.values(data.reduce((cats, v) => { v.category.forEach(c => { cats[c.id] = cats[c.id] || { id : c.id, title : c.title, titleFr : c.titleFr, stories : [] }; cats[c.id].stories.push(v.title); }); return cats; }, {})); console.log(categories);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.