how can I return just one element from an array from another file
where element (let say it's "2") is equal to id in that file
import { AnotherFile } from './AnotherFile'
const element = exFunc(element)
const exFunc = (val) => {
{AnotherFile.map((data) =>
data.id === parseInt(val) &&
return {data}
)}
}
This is the other file with data:
export const AnotherFile = [
{
id: 1,
text: 'Num 1',
},
{
id: 2,
text: 'Num 2',
},
{
id: 3,
text: 'Num 3',
}
]
Ps. More exactly i need a "text" value
alert("The text is: " + <>text value of data with id=2 from AnotherFile<>)
It doesn't work with && like that in the function, you would need to do a proper logic block:
const exFunc = (val) => {
AnotherFile.map((data) => {
if (data.id === parseInt(val)) return { data };
});
};
You can try to use the filter method for this. Please note the "?" operator to be sure that you don't try to access an item that does not exist
const exFunc = (val) => AnotherFile.filter((v) => v.id === val)[0]?.text;
console.log(exFunc(2));
This part :
data.id === parseInt(val) &&
return {data}
don't work inside a function
Try this :
if(data.id === parseInt(val)) return {data}