Tengo esta matriz:
const options = [ { uuid: '123312', label: 'hello' }, { uuid: '523312', label: 'there' } ]; Que necesito convertir en esto: { result: { [uuid-label]: number } }
result: { '123312-hello': 10 // this is just a random number for now '523312-there': 20 }El código que tengo hasta ahora es este:
const randomIntFromInterval = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1) + min); const [result, setResult] = useState<Result>({} as Result); useEffect(() => { if(options.length) { setResult( options.map(o => { return { [`${o.uuid}-${o.label}`]: randomIntFromInterval(0, 500) } })) } }, [options]); Pero ese código anterior está creando una matriz, como [{'123312-hello': 10}, {'523312-there': 20}]
Verifique el fragmento de código:
const options = [{ uuid: '123312', label: 'hello', sortOrder: 0 }, { uuid: '523312', label: 'there', sortOrder: 1 } ]; const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); const check = options.map(o => { return { [`${o.uuid}-${o.label}`]: randomIntFromInterval(0, 500) } }); console.log(check);Entonces, ¿qué me estoy perdiendo?
Parece un buen candidato para Object.fromEntries :
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); const options = [{uuid: '123312',label: 'hello'},{uuid: '523312', label: 'there'}]; const result = Object.fromEntries(options.map(({uuid, label}) => [`${uuid}-${label}`, randomIntFromInterval(0, 500)] )); console.log(result);Puedes usar reduce en lugar de map :
const options = [{ uuid: '123312', label: 'hello', sortOrder: 0 }, { uuid: '523312', label: 'there', sortOrder: 1 } ]; const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); const check = options.reduce((acc, o) => { acc[`${o.uuid}-${o.label}`] = randomIntFromInterval(0, 500); return acc; }, {}); console.log(check);