I have a array of objects. I want to merge the objects into a single array and use one of the value as key. In the example below I have a data array which I'm getting from the server as a response to a API and I want to use call_id as a key to index the response into a new array.
I've tried:
data.map(function(index, elem) {responses[index.call_id] = index;})
but this obviously only gets the last array and adding a [] gives me an error
Current Array:
[
{
"id": 2,
"survey_id": 1,
"question_id": 2,
"response": 1,
"order_id": null,
"customer_id": 1,
"call_id": 108,
"created_at": "2020-02-20 18:18:47",
"updated_at": "2020-02-20 18:18:47",
"question": "Do you want it gift wrapped?",
"first_name": "Zain",
"sid": "CA1564cda12b7e1364dc967538c7bdf617"
},
{
"id": 1,
"survey_id": 1,
"question_id": 1,
"response": 2,
"order_id": null,
"customer_id": 1,
"call_id": 108,
"created_at": "2020-02-20 18:18:32",
"updated_at": "2020-02-20 18:18:32",
"question": "Is your order confirmed?",
"first_name": "Zain",
"sid": "CA1564cda12b7e1364dc967538c7bdf617"
},
{
"id": 1,
"survey_id": 1,
"question_id": 1,
"response": 2,
"order_id": null,
"customer_id": 1,
"call_id": 109,
"created_at": "2020-02-20 18:18:32",
"updated_at": "2020-02-20 18:18:32",
"question": "Is your order confirmed?",
"first_name": "Zain",
"sid": "CA1564cda12b7e1364dc967538c7bdf617"
}
]
Expected Result
[{
'108': [
{
"id": 2,
"survey_id": 1,
"question_id": 2,
"response": 1,
"order_id": null,
"customer_id": 1,
"call_id": 108,
"created_at": "2020-02-20 18:18:47",
"updated_at": "2020-02-20 18:18:47",
"question": "Do you want it gift wrapped?",
"first_name": "Zain",
"sid": "CA1564cda12b7e1364dc967538c7bdf617"
},
{
"id": 1,
"survey_id": 1,
"question_id": 1,
"response": 2,
"order_id": null,
"customer_id": 1,
"call_id": 108,
"created_at": "2020-02-20 18:18:32",
"updated_at": "2020-02-20 18:18:32",
"question": "Is your order confirmed?",
"first_name": "Zain",
"sid": "CA1564cda12b7e1364dc967538c7bdf617"
}
],
'109' : [
{
"id": 1,
"survey_id": 1,
"question_id": 1,
"response": 2,
"order_id": null,
"customer_id": 1,
"call_id": 109,
"created_at": "2020-02-20 18:18:32",
"updated_at": "2020-02-20 18:18:32",
"question": "Is your order confirmed?",
"first_name": "Zain",
"sid": "CA1564cda12b7e1364dc967538c7bdf617"
}
]
}]
data.map(function(index, elem) {responses[index.call_id] = index;})but this obviously only gets the last array and adding a[]gives me an error.