I need to create two results from body_Task depending on the Header_Tasks.type
Header_Tasks
[
{"_id":"AAA54" "title":"task 1" "type":1},
{"_id":"bbb45" "title":"task 2" "type":2},
{"_id":"ccc56" "title":"task 3" "type":1},
{"_id":"xxx98" "title":"task 4" "type":2},
]
I have been created it depending on Header_Tasks, its name is body_taks, I save the data (header, body) in my database because it has other functions on my project
body_taks
{
"AAA54":10,
"AAA54|max":10,
"bbb45":07,
"bbb45|max":20,
"ccc56":05,
"ccc56|max":30,
"xxx98":03,
"xxx98|max":15,
}
I wish it, two results depending on Header_Tasks.type
type 1
{
"AAA54":10,
"AAA54|max":10,
"ccc56":05,
"ccc56|max":30,
}
type 2
{
"bbb45":07,
"bbb45|max":20,
"xxx98":03,
"xxx98|max":15,
}
This can be done with a fairly standard 'group by' first creating a Map to look up types against, then grouping by type in the result object.
const headerTasks = [{ _id: "AAA54", title: "task 1", type: 1 }, { _id: "bbb45", title: "task 2", type: 2 }, { _id: "ccc56", title: "task 3", type: 1 }, { _id: "xxx98", title: "task 4", type: 2 },];
const bodyTasks = { AAA54: 10, "AAA54|max": 10, bbb45: "07", "bbb45|max": 20, ccc56: "05", "ccc56|max": 30, xxx98: "03", "xxx98|max": 15, };
const typeMap = new Map(headerTasks.map((t) => [t._id, t.type]));
const result = {};
for (const key in bodyTasks) {
const id = key.includes("|") ? key.slice(0, key.indexOf("|")) : key;
const t = typeMap.get(id);
if (t !== undefined) {
result[`type${t}`] ??= {};
result[`type${t}`][key] = bodyTasks[key];
}
}
console.log(result);
Note: I have converted the numbers prefaced with 0 to strings as [octal literals] are not allowed in strict mode and I wasn't sure if you intended them as octals.