I want to set value to array if name have index, I have data like this:
[
{
"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": "[email protected]"
}
]
and I want to modify the name and value to array result if name have index, the result should 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": "[email protected]"
}
]
I have try to do that whit this, but it doest work
const res = array?.reduce(
(accumulator, value) => ({
...accumulator,
[value.name?.split("[").shift()]: value.value,
}),
{}
);
console.log(res)
3
Answers
Something like this – note the Nullish coalescing assignment ??=
Faster example?