1
\$\begingroup\$
const getSelectedItemsIds = selectedItemsList => { let keys = Object.keys(selectedItemsList); let selectedItems = []; keys.map(k => { selectedItemsList[k].map(id => { if (k.includes("projectIds")) { return selectedItems.push({ type: "PROJECT", id }); } else if (k.includes("subjectGroupIds")) { return selectedItems.push({ type: "SUBJECT_GROUP", id }); } else if (k.includes("subjectIds")) { return selectedItems.push({ type: "SUBJECT", id }); } }); }); return selectedItems; } 

I have written my custom logic to get the desired result, if anyone can validate and tell me if there's a better way to do it. I'm adding input and expected out below:

I/P: { projectIds: [2] subjectGroupIds: [] // incase multiple subjects are grouped togehter subjectIds: [4] } Expected format: [{"type":"PROJECT","id":2},{"type":"SUBJECT","id":4}] 

Thanks in advance!

\$\endgroup\$

    1 Answer 1

    1
    \$\begingroup\$

    Your code is not bad. You use functional style to loop through the data, which is good. But inside the loop you do not have to check with if-elseif-elseif, as this is not solid when it comes to many many cases. Maybe it would be better to use a map object to guide the process of matching data.

    getSelectedItemsIds = selectedItemsList => { const keyNamesMap = { projectIds: "PROJECT", subjectGroupIds: "SUBJECT_GROUP", subjectIds: "SUBJECT" }; let selectedItems = []; Object.keys(keyNamesMap).map( k => { selectedItemsList[k].map ( id => { selectedItems.push ( { type: keyNamesMap[k], id: id } ); }); }); return selectedItems; } 

    This way it is more clear and more easy to add another type.

    \$\endgroup\$

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.