user3105927 user3105927 - 3 months ago 13
JSON Question

Create an array of Objects from JSON

I have a JSON file like below:

[

{"fields":{category_class":"CAT2",category_name":"A"},"pk":1 },

{"fields":{category_class":"CAT1",category_name":"B"},"pk":2 },

{"fields":{category_class":"CAT1",category_name":"C"},"pk":3 },

{"fields":{category_class":"CAT2",category_name":"D"},"pk":4 },

{"fields":{category_class":"CAT3",category_name":"E"},"pk":5 },

{"fields":{category_class":"CAT1",category_name":"E"},"pk":6 },

]


I want to create an array of objects from the above JSON which will have two properties. i) CategoryClass ii) CategoryNameList. For example:

this.CategoryClass = "CAT1"
this.CategoryNameList = ['B','C','E']


Basically i want to select all categories name whose category class is CAT1 and so forth for other categories class. I tried this:

var category = function(categoryClass, categoryNameList){

this.categoryClass = categoryClass;
this.categoryList = categoryNameList;

}

var categories = [];

categories.push(new category('CAT1',['B','C','E'])


Need help.

Answer

I would suggest this ES6 function, which creates an object keyed by category classes, providing the object with category names for each:

function groupByClass(data) {
    return data.reduce( (acc, { fields } ) => {
        (acc[fields.category_class] = acc[fields.category_class] || {
            categoryClass: fields.category_class,
            categoryNameList: []
        }).categoryNameList.push(fields.category_name);
        return acc;
    }, {} );
}

// Sample data
var data = [
    {"fields":{"category_class":"CAT2","category_name":"A"},"pk":1 },
    {"fields":{"category_class":"CAT1","category_name":"B"},"pk":2 },
    {"fields":{"category_class":"CAT1","category_name":"C"},"pk":3 },
    {"fields":{"category_class":"CAT2","category_name":"D"},"pk":4 },
    {"fields":{"category_class":"CAT3","category_name":"E"},"pk":5 },
    {"fields":{"category_class":"CAT1","category_name":"E"},"pk":6 },
];
// Convert
var result = groupByClass(data);
// Outut
console.log(result);
// Example look-up:
console.log(result['CAT1']);

Comments