简体   繁体   中英

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

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

Category 27- AAA

This is a Story title

Category 43 - XXX

This is a Story title

This is a Story title 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?

I feel like there's a lot of looping here and using $.each would be very inefficient.

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. You can then use Object.values to convert the result object into an array:

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM