I have a an array of objects like this:
[{
grade: 1,
title: 'TitleA',
code_no: 1,
code_name: 'A',
business_number: '',
total_sales_count: 213,
general_number: 0,
resident_number: 20,
address: '',
},
{
grade: 2,
title: 'TitleB',
code_no: 1,
code_name: 'A',
business_number: '',
total_sales_count: 300,
general_number: 0,
resident_number: 12,
address: '',
},
{
grade: 3,
title: 'TitleC',
code_no: 1,
code_name: 'A',
business_number: '',
total_sales_count: 221,
general_number: 0,
resident_number: 9,
address: '',
},
...
]
and I was trying to refactor the objects like this:
[{
grade: 1,
title: 'TitleA',
type : {code_no: 1, code_name: 'A'},
business_number: '',
counts: {
total_sales_count: 213,
general_number: 0,
resident_number: 20
},
address: '',
},
{
grade: 2,
title: 'TitleB',
type: {code_no: 1, code_name: 'A'},
business_number: '',
counts: {
total_sales_count: 300,
general_number: 0,
resident_number: 12
},
address: '',
},
{
grade: 3,
title: 'TitleC',
type: {code_no: 1, code_name: 'A'},
business_number: '',
counts: {
total_sales_count: 221,
general_number: 0,
resident_number: 9
},
address: '',
},
...
]
So, in first time, I just used a map method like this
const test: any = data.map((i: any) => {
const obj: any = {
...i,
type: {
code_no: i.code_no,
code_name: i.code_name,
},
counts: {
total_sales_count: i.total_sales_count,
general_number: i.general_number,
resident_number: i.resident_number
},
};
return obj;
});
and tried to remove the duplicated data from the array, but I think it's not quite right approach to change the structure of the array...(because I have to change the data multiple times, not at once.)
I'm very new to javascript so I think there's more efficient way to restructure format but couldn't catch a clue. Is there any way to change the structure of an array of objects?