I need to make .map to display label name and after when i get id from map i need to filter where id from .map is same in second array and display all same ids
FIRST array to .map
[{"id":"14","name":"Certifikace"},{"id":"17","name":"Instalace"}]
SECOND array to .filter with id from first array
[{"filter_name_id":"14","text":"CE"},{"filter_name_id":"14","text":"PZTS"},{"filter_name_id":"14","text":"Železnice"},{"filter_name_id":"17","text":"Volný podklad"},{"filter_name_id":"17","text":"DIN35"},{"filter_name_id":"17","text":"Do 10\" stojanu"},{"filter_name_id":"17","text":"Do 19\" stojanu"},{"filter_name_id":"17","text":"Na sloup"}]
My current code
{
filterListDataName &&
filterListDataName.map(
function (item, id) {
return (
<label>{item.name}</label>
//here need to add filter with (item.id) from filterListDataText.filter()
);
}.bind(this)
);
}
Thank you.
CodePudding user response:
If the data we set as dataName and dataNameText:
const dataName = [
{"id":"14","name":"Certifikace"},
{"id":"17","name":"Instalace"}
];
const dataNameText = [
{"filter_name_id":"14","text":"CE"},
{"filter_name_id":"14","text":"PZTS"},
{"filter_name_id":"14","text":"Železnice"},
{"filter_name_id":"17","text":"Volný podklad"},
{"filter_name_id":"17","text":"DIN35"},
{"filter_name_id":"17","text":"Do 10\" stojanu"},
{"filter_name_id":"17","text":"Do 19\" stojanu"},
{"filter_name_id":"17","text":"Na sloup"}
];
then the filteredDataNameText name will be:
return (
...
<ul>
{dataName.map((item) => {
return (
<li>
<label>{item.name}</label>
<ul>
{dataNameText
.filter((dT) => dT.filter_name_id === item.id)
.map((filtered) => {
return <li>{filtered.text}</li>;
})}
</ul>
</li>
);
})}
</ul>
...
)
But if you use functional component, you can use useMemo to memoize the filtered data:
const listDataName = useMemo(() => {
return dataName.map((data) => {
return {
...data,
dataText: dataText.filter((dt) => dt.filter_name_id === data.id)
};
});
}, []);
and render it as follows:
return (
<>
...
<ul>
{listDataName.map((item) => {
return (
<li>
<label>{item.name}</label>
<ul>
{item.dataText.map((dtText) => {
return <li>{dtText.text}</li>;
})}
</ul>
</li>
);
})}
</ul>
...
</>
)