如何從另一個檔案的陣列中只回傳一個元素,其中元素(假設它是"2")等于該檔案中的 id
import { AnotherFile } from './AnotherFile'
const element = exFunc(element)
const exFunc = (val) => {
{AnotherFile.map((data) =>
data.id === parseInt(val) &&
return {data}
)}
}
這是另一個包含資料的檔案:
export const AnotherFile = [
{
id: 1,
text: 'Num 1',
},
{
id: 2,
text: 'Num 2',
},
{
id: 3,
text: 'Num 3',
}
]
附言。更確切地說,我需要一個“文本”值
alert("The text is: " <>text value of data with id=2 from AnotherFile<>)
uj5u.com熱心網友回復:
它不適&&用于函式中的那樣,您需要做一個適當的邏輯塊:
const exFunc = (val) => {
AnotherFile.map((data) => {
if (data.id === parseInt(val)) return { data };
});
};
uj5u.com熱心網友回復:
您可以嘗試為此使用過濾器方法。請注意“?” 操作員以確保您不會嘗試訪問不存在的專案
const exFunc = (val) => AnotherFile.filter((v) => v.id === val)[0]?.text;
console.log(exFunc(2));
uj5u.com熱心網友回復:
您可以使用查找方法
let files = [{id:1}, {id:2}]
cofiles.find( file => file.id == 1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486461.html
標籤:javascript 反应
