I have one obj that I received from the client,
const record = {
"date":"2021-09-20",
"startAt":"10:00",
"endAt":"16:00",
"employeeId": [5,2],<==
"projectId":[50,48],<==
"notes":"blahhh"
}
I want to convert it to some objects, same details , but I want for example employeeId 5 worked in two projects, 50 and 48 I want to have two objects with same details but the employeeId is 50 and the projectId : first object with 50 and the sec obj with 48
{
....
"employeeId": [5],<== //first emplyee
"projectId":[50],<== // first project
....
}
{
....
"employeeId": [5],//first emplyee
"projectId":[48], // sec project
...
}
{
....
"employeeId": [2],//sec employee
"projectId":[50], //first project
....
}
{
....
"employeeId": [2],//sec employee
"projectId":[48], //sec project
....
}
thank you for helping me
CodePudding user response:
You can do for example:
const record = {
date: "2021-09-20",
startAt: "10:00",
endAt: "16:00",
employeeId: [5, 2],
projectId: [50, 48],
notes: "blahhh",
};
const records = record.employeeId
.map((employeeId) =>
record.projectId.map((projectId) => ({
...record,
employeeId: [employeeId],
projectId: [projectId]
}))
)
.flat();
console.log(records);
CodePudding user response:
1- Extract all of keys which have array values
let arrayKeys = Object.entries(record).filter(([key, value]) => typeof value === 'object' && Array.isArray(value))
2- Create your default object with default keys:
let defaultObj = Object.entries(record).reduce((obj, [key, value]) => {
if(!typeof value === 'object' || !Array.isArray(value)) {
obj[key] = value
}
return obj;
}, {})
3- Create a function which fill an array with your final objects recursively:
function addKeys(array, obj, keys) {
if(!keys.length) {
array.push(obj);
return;
}
let [key, values] = keys.pop();
values.forEach(val => {
obj[key] = [val];
addKeys(array, {...obj}, [...keys])
});
}
Full code:
const record = {
"date":"2021-09-20",
"startAt":"10:00",
"endAt":"16:00",
"employeeId": [5,2],
"projectId":[50,48, 60, 70],
"notes":"blahhh",
"extraArrayKey": ['a', 'b']
}
let arrayKeys = Object.entries(record).filter(([key, value]) => typeof value === 'object' && Array.isArray(value))
let defaultObj = Object.entries(record).reduce((obj, [key, value]) => {
if(!typeof value === 'object' || !Array.isArray(value)) {
obj[key] = value
}
return obj;
}, {})
function addKeys(array, obj, keys) {
if(!keys.length) {
array.push(obj);
return;
}
let [key, values] = keys.pop();
values.forEach(val => {
obj[key] = [val];
addKeys(array, {...obj}, [...keys])
});
}
let output = [];
addKeys(output, defaultObj, arrayKeys)
console.log(output)