I have below data from my API call and I am working with reduce function to set data as per my requirement. But not able to produce it, please check below code and required output. Also check the function I am trying and suggest me way to create the response.
API Response:
let cmpRecords = {
"status": "success",
"message": "Record Fetched Successfully",
"data": [
{
"_id": "6098ff60a8e9ee2c7c116d6e",
"record": {
"creatorName": "ABC",
"modifierName": ""
},
"is_deleted": "0"
},
{
"_id": "6098ff60a8e9ee2c7c116d6e",
"record": {
"creatorName": "ABC",
"modifierName": ""
},
"is_deleted": "0"
},
{
"_id": "6098ff60a8e9ee2c7c116d6z",
"record": {
"creatorName": "XYZ",
"modifierName": ""
},
"is_deleted": "0"
},
...
]
}
Required Output ::
{
"status": "success",
"message": "Record Fetched Successfully",
"data": [
{
"name": "ABC",
"record": [
{
"_id": "6098ff60a8e9ee2c7c116d6e",
"record": {
"creatorName": "ABC",
"modifierName": ""
},
"is_deleted": "0"
},
{
"_id": "6098ff60a8e9ee2c7c116d6e",
"record": {
"creatorName": "ABC",
"modifierName": ""
},
"is_deleted": "0"
}
]
},
{
"name": "XYZ",
"record": [
{
"_id": "6098ff60a8e9ee2c7c116d6z",
"record": {
"creatorName": "XYZ",
"modifierName": ""
},
"is_deleted": "0"
}
]
}
]
}
As I want to seperate record of same user, with key and value & key and object I used reduce function for this
group = cmpRecords.reduce((r, a) => {
let name = a.record.creatorName;
let record = a;
r[name] = [...r[name] || [], record];
return r;
}, {});
This responds with
"data": [
"ABC":[
{
"_id": "6098ff60a8e9ee2c7c116d6e",
"record": {
"creatorName": "ABC",
"modifierName": ""
},
"is_deleted": "0"
},
...
]
]
I tried other ways but not getting required response.
datashould be an array of Objects where each would have bothnameandrecordas attributes.