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!

asked Feb 26, 2020 at 7:36
\$\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.

answered Feb 26, 2020 at 8:57
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.