I have below json
let result = [
{
"category": "Social Media",
"category_id": 6,
"sub_category": "Facebook",
"sub_category_id": 5
},
{
"category": "Social Media",
"category_id": 6,
"sub_category": "Instagram",
"sub_category_id": 7
},
{
"category": "Tech",
"category_id": 3,
"sub_category": "Angular",
"sub_category_id": 1
},
{
"category": "Tech",
"category_id": 3,
"sub_category": "Javascript",
"sub_category_id": 6
}
]
I am trying to active below
[
{
"category": "Social Media",
"category_id": 6,
"sub_category": [
{
"sub_category": "Instagram",
"sub_catgory_id": 7
},
{
"sub_category": "Facebook",
"sub_catgory_id": 5
}
]
},
{
"category": "Tech",
"category_id": 3,
"sub_category": [
{
"sub_category": "Angular",
"sub_catgory_id": 1
},
{
"sub_category": "Javascript",
"sub_catgory_id": 6
}
]
}
]
Below code i have tried. Can anyone help me to identify where i am doing wrong?
let result = [{
"category": "Social Media",
"category_id": 6,
"sub_category": "Facebook",
"sub_category_id": 5
},
{
"category": "Social Media",
"category_id": 6,
"sub_category": "Instagram",
"sub_category_id": 7
},
{
"category": "Tech",
"category_id": 3,
"sub_category": "Angular",
"sub_category_id": 1
},
{
"category": "Tech",
"category_id": 3,
"sub_category": "Javascript",
"sub_category_id": 6
}
];
const dataArr = [];
result.forEach((value, key) => {
let catgeory = {
category: value.category,
category_id: value.category_id,
sub_category: []
};
catgeory.sub_category.push({
sub_category: value.sub_category,
sub_category_id: value.sub_category_id
})
dataArr.push(catgeory);
});
console.log(dataArr);
Explanation is in comments.
const data = {}
let result = [{"category":"Social Media","category_id":6,"sub_category":"Facebook","sub_category_id":5},{"category":"Social Media","category_id":6,"sub_category":"Instagram","sub_category_id":7},{"category":"Tech","category_id":3,"sub_category":"Angular","sub_category_id":1},{"category":"Tech","category_id":3,"sub_category":"Javascript","sub_category_id":6}];
// loop over each records
result.forEach((value) => {
// data will be object with key as category and value as category, category_id & sub_category array.
// get data[value.category], if not exist then create new object and assign.
data[value.category] = data[value.category] || {
category: value.category,
category_id: value.category_id,
sub_category: []
};
// push sub_category values.
data[value.category].sub_category.push({
sub_category: value.sub_category,
sub_category_id: value.sub_category_id
});
});
// we need array of values only so use Object.values(data)
let dataArr = Object.values(data);
console.log(dataArr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With