Reputation: 4054
I am using react-select
for the select field. When i use normal map
function, the options are shown but if I use nested map
function it does not list the options.
Here is what I have done
<Field
name="subjects"
label="Destination Subjects *"
component={SelectField}
isSearchable
isMulti
options={get(props, "destinations").map(destination => {
return preferredDestination.map(pdes => {
if (destination._id === pdes.name) {
if (get(destination, "subjects").length > 0) {
return get(destination, "subjects").map(
(subject, idx) => {
console.log("subject", subject); // it gets printed too
return {
name: subject.id,
value: subject.val
};
}
);
} else {
return [];
}
} else {
return [];
}
});
})}
/>
This does not list any options but I want options based on certain conditions only.
<Field
name="subjects"
label="Destination Subjects *"
component={SelectField}
isSearchable
isMulti
options={get(props, "destinations").map(destination => {
return {
name: destination.name,
value: destination.value,
}
})}
/>
By normal map
function i was meant to say the above code. This one works but this is not what I want. I want those items as option which matches the subject for particular selected destination only not the subjects of all the destinations.
How can I now show the options based on the conditions like above?
I am getting the following in options while debugging
Here is the screenshot of what I am getting with vijay's solution
Upvotes: 0
Views: 1222
Reputation: 3604
Just make sure the resulting array is one dimensional and use label
for name and value
for value
Here is the code
<Field
name="subjects"
label="Destination Subjects *"
component={SelectField}
isSearchable
isMulti
options={get(props, "destinations").map(destination => {
// Don't use second map here
// if you're just trying to find the matching element
// in the second array
if (
preferredDestination.findIndex(
pdes => destination._id === pdes.name
) >= 0
) {
if (get(destination, "subjects").length > 0) {
return get(destination, "subjects").map(
(subject) => {
return {
label: subject.id, // change it to label
value: subject.val
};
}
);
}
}
// remove unwanted else block
return null
})
.filter(x => x !== null) // remove null elements
.reduce((a, c) => [...a, ...c], []) // this will convert the 2D array to 1D
}
/>
Upvotes: 1