I am attempting to create a mapped array with keys similar to the structure below
const data = [{
"_id": "5f0ffb96d67d70c1a3b143e7",
"name": "USER",
"type": "CUSTOM",
"origin": "USER",
"conditions": [{
"_id": "5f0ffb96d67d70c1a3b143e8",
"field": "status",
"value": "Nomita",
"operator": "equal"
}, {
"_id": "5f0ffb96d67d70c1a3b143e9",
"field": "current_status",
"value": "ACTIVE",
"operator": "equal"
}, {
"_id": "5f0ffb96d67d70c1a3b143ea",
"field": "user_group_uuid",
"value": "d12s0a7c-11ac-7abf-bl03-f0b70e26f8f2",
"operator": "equal"
}, {
"_id": "5f0ffb96d67d70c1a3b143eb",
"field": "user_group_uuid",
"value": "20348751-dcaa-4227-a0ff-912b27180aee",
"operator": "equal"
}]
}]
The above code snippet shows the input.
const filters_data = { ...data[0] }
const filters_mapping = (array, keyField) =>
array.reduce((obj, item) => {
obj[item[keyField]] = item
return obj
}, {})
const filter_items = filters_mapping(filters_data.conditions,'field');
By executing this code, I am currently receiving the following output:
{ user_status:
{ _id: 5f0ffb96d67d70c1a3b143e8,
field: 'status',
value: 'Nomita',
operator: 'equal' },
current_status:
{ _id: 5f0ffb96d67d70c1a3b143e9,
field: 'current_status',
value: 'ACTIVE',
operator: 'equal' },
user_group_uuid:
{ _id: 5f0ffb96d67d70c1a3b143eb,
field: 'user_group_uuid',
value: 'd12s0a7c-11ac-7abf-bl03-f0b70e26f8f2',
operator: 'equal' } }
However, what I truly desire is a result like this, where the value
is an array when multiple values are available for a single field:
{ user_status:
{ _id: 5f0ffb96d67d70c1a3b143e8,
field: 'status',
value: ['Nomita'],
operator: 'equal' },
current_status:
{ _id: 5f0ffb96d67d70c1a3b143e9,
field: 'current_status',
value: ['ACTIVE'],
operator: 'equal' },
user_group_uuid:
{ _id: 5f0ffb96d67d70c1a3b143eb,
field: 'user_group_uuid',
value: ['d12s0a7c-11ac-7abf-bl03-f0b70e26f8f2','20348751-dcaa-4227-a0ff-912b27180aee'],
operator: 'equal' } }
This alteration should only occur when there are multiple fields present. Otherwise, a singular string should be returned as per usual.