Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
¿Cómo puedo crear un objeto basado en las claves de una matriz?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!