我有以下兩個陣列:
const dates = [ "January 1st, 2022", "January 2nd, 2022", More dates...]
const events = [
{
id: 1,
date: "January 10th, 2022",
title: "Have a meeting",
}
More events...
]
我想做的是映射日期陣列,顯示所有日期,并映射事件陣列并在 event.date 與日期陣列中的相應日期匹配時顯示 event.title .. 如何映射事件帶有日期陣列的陣列以及日期匹配時輸出 event.title?
目前我有這個:
{dates.map((date, i) => (
<li
key={i}
>
{date}
//Here I would also like to display the {event.title} when the dates match.
</li>
))}
uj5u.com熱心網友回復:
(使用可選鏈接運算子 (?.))
{dates.map((date, i) => (
<li
key={i}
>
{events.find(e => e.date == date)?.title}
</li>
))}
uj5u.com熱心網友回復:
import logo from './logo.svg';
import './App.css';
const dates = [ "January 1st, 2022", "January 2nd, 2022", ]
const events = [
{
id: 1,
date: "January 1st, 2022",
title: "Have a meeting",
},
{
id: 1,
date: "January 2nd, 2022",
title: "second meeting",
},
{
id: 1,
date: "January 3rd, 2022",
title: "Have a meeting",
}
]
function App() {
return (
<div className="App">
{dates.map((date, i) => (
<li
key={i}
>
{events.map((data,i)=> {
console.log(data,date,"data...")
return (
<div>
{data.date == date ?
<div>Here I would also like to display the {data.title} when the dates match.</div>
:null}
</div>
)})}
</li>
))}
</div>
);
}
export default App;
uj5u.com熱心網友回復:
我只是在此處添加邏輯以獲取過濾后的陣列,該陣列僅包含基于我們在dates&events陣列中進行的比較的標題。
const dates = ["January 1st, 2022", "January 2nd, 2022"];
const events = [{
id: 1,
date: "January 1st, 2022",
title: "Have a meeting 1st January",
}, {
id: 2,
date: "January 10th, 2022",
title: "Have a meeting 10th January",
}, {
id: 2,
date: "January 2nd, 2022",
title: "Have a meeting 2nd January",
}];
const res = events.filter((obj) => dates.includes(obj.date)).map((obj) => obj.title);
console.log(res);
uj5u.com熱心網友回復:
如果您所有的日期都是字串并且它們與dates陣列中的字串匹配,那么您可以將您的事件構造為一個物件,其中鍵是日期。(這是假設沒有重疊事件)。
這種方法的好處是你只有兩個回圈,這使得代碼非常高效。
const structuredEvents = events.reduce((acc, cur => {
acc[cur.date] = cur;
return acc;
}, {});
在您的回圈中,根據date.
{dates.map((date, i) => {
const event = structuredEvents[date];
return (
<li
key={i}
>
{date}
{event?.title}
</li>
);
})}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/435738.html
標籤:javascript 数组 反应 ecmascript-6
上一篇:映射減少物件陣列的計數和總和
