I am pulling data from Excel using JavaScript. The output looks like this.
{
"Responsible": "Grey",
"Goal": 0.823,
"Jan": 0.8621397507374327,
"Feb": 0.8605700219733681,
"Mrz": 0.8870898346258058,
"Apr": 0.8529801908413164,
"Mai": 0.8507431241640211
}
I want to split the data into the following :
{
"Responsible": "Grey",
"Goal": 0.823,
"Month": 0.8621397507374327,
}
{
"Responsible": "Grey",
"Goal": 0.823,
"Month": 0.8605700219733681,
}
{
"Responsible": "Grey",
"Goal": 0.823,
"Month": 0.8870898346258058,
}
{
"Responsible": "Grey",
"Goal": 0.823,
"Month": 0.8529801908413164,
}
{
"Responsible": "Grey",
"Goal": 0.823,
"Month": 0.8507431241640211
}
My code looks like this :
Ausgabe = [];
_.forEach(data, element => {
obj = {
Responsible: element.Responsible,
Goal: element["Goal \r\n2022"] ,
Jan : element["Jan-22"],
Feb: element["Feb-22"],
Mrz : element["Mar-22"],
Apr : element["Apr-22"],
Mai : element["May-22"],
}
Ausgabe.push(obj)
})
The data is provided in the data field, which can be edited or overwritten and is returned by default at the end.
Use destructuring to extract Responsible, Goal and the rest of the object's properties. Use Object.entries() to get an array of [key, value] pairs from rest, and iterate it with Array.map() to create the objects:
const fn = ({ Responsible, Goal, ...rest }) =>
Object.entries(rest)
.map(([k, v]) => ({
Responsible,
Goal,
[k]: v
}))
const obj = { "Responsible": "Grey", "Goal": 0.823, "Jan": 0.8621397507374327, "Feb": 0.8605700219733681, "Mrz": 0.8870898346258058, "Apr": 0.8529801908413164, "Mai": 0.8507431241640211 }
const result = fn(obj)
console.log(result)
If you just want the month's value, use Object.values() instead of entries:
const fn = ({ Responsible, Goal, ...rest }) =>
Object.values(rest)
.map(Month => ({
Responsible,
Goal,
Month
}))
const obj = { "Responsible": "Grey", "Goal": 0.823, "Jan": 0.8621397507374327, "Feb": 0.8605700219733681, "Mrz": 0.8870898346258058, "Apr": 0.8529801908413164, "Mai": 0.8507431241640211 }
const result = fn(obj)
console.log(result)