así que tengo una matriz con todos los jugadores y una con solo el que está seleccionado y quiero tener otra matriz con el estado si está seleccionado o no. Traté de comparar y presionar el elemento con el estado, pero no logré lo que quería.
aquí están las matrices
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', }, ];y esto es lo que quiero lograr
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 }, ];Configuré un entorno para trabajar aquí: https://stackblitz.com/edit/react-lkcqcd?file=src%2FApp.js
¡gracias por la atención!
Puede usar Array#some para verificar si la identificación del jugador está en la matriz seleccionada.
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);Puede crear un conjunto de jugadores seleccionados y usar este conjunto puede agregar el campo de 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); También puede usar Array.prototype.find en lugar de crear un conjunto, pero esto no sería óptimo a menos que el tamaño de la matriz selected sea bastante pequeño.
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);Puede usar Array#map y Array#includes como en la siguiente demostración:
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 );