所以我有一個包含所有玩家的陣列,一個只有一個被選中的陣列,如果他被選中,我想要另一個陣列的狀態。我嘗試將元素與狀態進行比較和推送,但沒有達到我想要的。
這是陣列
const all = [
{
playerId: '294',
firstName: 'MMM',
},
{
playerId: '295',
firstName: 'arkiv',
},
{
playerId: '296',
firstName: 'julio',
},
{
playerId: '297',
firstName: 'sss',
},
];
const selected = [
{
playerId: '296',
firstName: 'julio',
},
{
playerId: '297',
firstName: 'sss',
},
];
這就是我想要實作的
const res = [
{ playerId: '294', firstName: 'MMM', status: false },
{ playerId: '295', firstName: 'arkiv', status: false },
{ playerId: '296', firstName: 'julio', status: true },
{ playerId: '297', firstName: 'sss', status: true },
];
我設定了一個在這里作業的環境:https ://stackblitz.com/edit/react-lkcqcd?file=src/App.js
感謝關注!
uj5u.com熱心網友回復:
您可以使用Array#some來檢查玩家的 id 是否在選定的陣列中。
const all=[{playerId:'294',firstName:'MMM',},{playerId:'295',firstName:'arkiv',},{playerId:'296',firstName:'julio',},{playerId:'297',firstName:'sss',},],selected=[{playerId:'296',firstName:'julio',},{playerId:'297',firstName:'sss',},];
all.forEach(player => player.status =
selected.some(x => x.playerId === player.playerId));
console.log(all);
uj5u.com熱心網友回復:
您可以創建一組選定的玩家,并使用該組添加該status欄位。
const
all = [{ playerId: "294", firstName: "MMM" }, { playerId: "295", firstName: "arkiv" }, { playerId: "296", firstName: "julio" }, { playerId: "297", firstName: "sss" }],
selected = [{ playerId: "296", firstName: "julio" }, { playerId: "297", firstName: "sss" }],
selectedSet = new Set(selected.map((player) => player.playerId)),
res = all.map((player) => ({ ...player, status: selectedSet.has(player.playerId) }));
console.log(res);
您也可以使用Array.prototype.find而不是創建一個集合,但這不是最佳選擇,除非selected陣列的大小非常小。
const
all = [{ playerId: "294", firstName: "MMM" }, { playerId: "295", firstName: "arkiv" }, { playerId: "296", firstName: "julio" }, { playerId: "297", firstName: "sss" }],
selected = [{ playerId: "296", firstName: "julio" }, { playerId: "297", firstName: "sss" }],
res = all.map((player) => ({
...player,
status: !!selected.find((selPlayer) => selPlayer.playerId === player.playerId),
}));
console.log(res);
uj5u.com熱心網友回復:
您可以在以下演示中使用Array#mapand :Array#includes
const all = [ { playerId: '294', firstName: 'MMM', }, { playerId: '295', firstName: 'arkiv', }, { playerId: '296', firstName: 'julio', }, { playerId: '297', firstName: 'sss', }, ],
selected = [ { playerId: '296', firstName: 'julio', }, { playerId: '297', firstName: 'sss', }, ],
output = all.map(
player =>
({
...player,
status:selected.map(({playerId}) => playerId)
.includes(player.playerId)
})
);
console.log( output );
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/491465.html
標籤:javascript 数组 json
上一篇:MongDB聚合兩個同名值
