My API will be sending back data in the following format:
[
{
"id":5,
"name":"Example",
},
{
"id":634,
"name":"Test",
},
...
]
In my React application, I need to create a JSON object like this:
const fields = [
{
title: 'Example',
type: 'select',
choices: [
{},
{ label: '1', value: '1' },
{ label: '2', value: '2' },
],
},
{
title: 'Test',
type: 'select',
choices: [
{},
{ label: '1', value: '1' },
{ label: '2', value: '2' },
],
},
...
]
The options will stay the same and are not based on the server response.
Is there a way to dynamically generate this JSON object depending on the API results?
Update
var origArray = [ {id:1, name: "aaa"},
{id:2, name: "bbb"},
{id:3, name: "ccc"},
{id:4, name: "ddd"}];
const fieldoptions = {
type: 'select',
choices: [
{},
{ label: '1', value: '1' },
{ label: '2', value: '2' },
]
};
const fields = origArray.map(item => ({
title: item.name,
fieldoptions
}));
console.log('fields');
console.log(fields)
The issue is that there is a parent element of fieldoptions
that should not appear in the output.
(4) [Object, Object, Object, Object] 0 : Object fieldoptions : Object title : "execution"