I am facing an issue with splitting/separating objects within an array. I know how to do it for a single object, but the challenge arises when dealing with an array of objects. The array structure is as follows:
[
{
"KPI": "Productivity [%] - Target",
"Area": "Plant",
"Jan22": 0.8621397507374327,
"Feb22": 0.8605700219733681,
"Mrz22": 0.8870898346258058
},
{
"KPI": "Productivity [%] - Target",
"Area": "Assembly",
"Jan22": 0.8817383050990651,
"Feb22": 0.8856950523200521,
"Mrz22": 0.9267495852228734
},
{
"KPI": "Productivity [%] - Target",
"Area": "Assembly CYU",
"Jan22" : 0.8984342053383161,
"Feb22": 0.9285678969440421,
"Mrz22": 0.9625283644615115
}
]
My goal is to split each object as shown below:
[
{
"KPI": "Productivity [%] - Target 0 ",
"Area": "Plant",
"Month": 0.8621397507374327
},
{
"KPI": "Productivity [%] - Target 1 ",
"Area">: "Plant",
"Month": 0.8605700219733681
},
{
"KPI": "Productivity [%] - Target 2 ",
"Area": "Plant",
"Month": 0.8870898346258058
}
{
"KPI": "Productivity [%] - Target 0 ",
"Area": "Assembly",
"Month": 0.8817383050990651
},
{
"KPI": "Productivity [%] - Target 1 ",
"Area": "Assembly",
"Month": 0.8856950523200521
},
{
"KPI": "Productivity [%] - Target 2 ",
"Area": "Assembly",
"Month": 0.9267495852228734
}
{
"KPI": "Productivity [%] - Target 0 ",
"Area": "Assembly CYU",
"Month": 0.8984342053383161
},
{
"KPI": "Productivity [%] - Target 1 ",
"Bereich": "Assembly CYU",
"Month": 0.9285678969440421
},
{
"KPI": "Productivity [%] - Target 2 ",
"Area": "Assembly CYU",
"Month": 0.9625283644615115
}
]
I have attempted using the following code snippet:
Ausgabe2 = [];
obj =
{
"KPI": "Productivity [%] - Target",
"Area": "Plant",
"Jan22": 0.8621397507374327,
"Feb22": 0.8605700219733681,
"Mrz22": 0.8870898346258058
},
{
"KPI": "Productivity [%] - Target",
"Area": "Assembly",
"Jan22": 0.8817383050990651,
"Feb22": 0.8856950523200521,
"Mrz22": 0.9267495852228734
},
{
"KPI": "Productivity [%] - Target",
"Area": "Assembly CYU",
"Jan22": 0.8984342053383161,
"Feb22": 0.9285678969440421,
"Mrz22": 0.9625283644615115
}
const fn = ({ KPI, Area, ...rest }) =>
Object.values(rest)
.map(Month => ({
KPI,
Area,
Month
}))
const result = fn(obj)
for (var i =0; i < result.length; i++){
obj2 = {
KPI : result[i].KPI + " " + i,
Bereich: result[i].Area,
Month : result[i].Month ,
}
Ausgabe2.push(obj2);
}
console.log(Ausgabe2);
However, I am not getting the desired output illustrated earlier. Instead, the current output is:
[ { KPI: 'Productivity [%] - Target 0',
Bereich: 'Plant',
Month: 0.8621397507374327 },
{ KPI: 'Productivity [%] - Target 1',
Bereich: 'Plant',
Month: 0.8605700219733681 },
{ KPI: 'Productivity [%] - Target 2',
Bereich: 'Plant',
Month: 0.8870898346258058 } ]
How can I modify the code to achieve the desired output?