Hello I'm stuck transforming this object to an object array.
There are the number and reason field, which are currently an ',' separated string. They should be exploded into their own object. The exampel dataset and what I want to archive can be seen in the codesnippet below.
// start value
const data = {
date: "2021-09-07 10:28:34,2021-09-08 14:45:22",
startDate: "2021-09-07 00:00:00,2021-09-08 14:45:22"
id: "111111"
number: "1,9"
reason: "Autres,Autres"
}
// what I want to archive:
const res = [{
date: "2021-09-07 10:28:34",
startDate: "2021-09-07 00:00:00",
id: 11111,
number: 1,
reason: "Autres"
} {
date: "2021-09-08 14:45:22",
startDate: "2021-09-08 14:45:22",
id: 11111,
number: 9,
reason: "Autres"
}]
Project the original object with string-combined-columns into an object with splitted columns as arrays using reduce method and spread operator.
1a. extract column names from original object by filtering out id column.
1b. In the process of projection, count the amount of rows.
Iterate over rows using the above counter, generating a new object for each row, taking relevant column value using current iteration index.
const original = {
date: "2021-09-07 10:28:34,2021-09-08 14:45:22",
startDate: "2021-09-07 00:00:00,2021-09-08 14:45:22",
id: "111111",
number: "1,9",
reason: "Autres,Autres"
};
function split(obj) {
const columnNames = Object.keys(obj).filter(key => key !== "id");
const singleWithSplitted = columnNames.reduce((result, columnName) => {
const splittedArray = obj[columnName].split(",");
return ({
rowsCount: Math.max(result.rowsCount, splittedArray.length),
table: { ...result.table,
[columnName]: splittedArray
}
});
}, {
rowsCount: 0
});
const arr = [];
for (i = 0; i < singleWithSplitted.rowsCount; i++) {
const result = {
id: obj.id
};
columnNames.forEach((columnName) => {
result[columnName] = singleWithSplitted.table[columnName][i];
});
arr.push(result);
};
return arr;
}
console.log(split(original));