How can I set values to an array if it has an index in the name field? Here is the sample data:
[
{
"column": "created_at[0]",
"name": "created_at[0]",
"type": "range",
"value": "2022-12-26 00:00:00"
},
{
"column": "created_at[1]",
"name": "created_at[1]",
"type": "range",
"value": "2023-12-26 23:59:59"
},
{
"column": "email",
"name": "email",
"type": "like",
"value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9dfcfcddfaf0fcf4f1b3fef2f0">[email protected]</a>"
}
]
I need to update both the name and value of the array if the name contains an index. The expected result should look like this:
[
{
"column": "created_at",
"name": "created_at",
"type": "range",
"value": ["2022-12-12 00:00:00", "2023-12-12 23:59:59"]
},
{
"column": "email",
"name": "email",
"type": "like",
"value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b1a1a3b1c161a121755181416">[email protected]</a>"
}
]
I have attempted to achieve this using the following code, but it isn't working as expected:
const modifiedArray = array?.reduce(
(accumulator, element) => ({
...accumulator,
[element.name?.split("[").shift()]: element.value,
}),
{}
);
console.log(modifiedArray)