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

130
Views
Reduciendo una matriz a un objeto en Javascript

Quiero convertir el siguiente objeto

 const order = { apple: 5, banana: 5, orange: 5 };

en el siguiente objeto, a cada tecla se le asigna su índice en el objeto como su valor

 { apple: 0, banana: 1, orange: 2 }

Este es el código que tengo pero no funciona y no sé por qué.

 const indices = Object.keys(order).reduce( (previousValue, currentValue, currentIndex) => (previousValue[currentValue] = currentIndex), {} ); TypeError: Cannot create property 'banana' on number '0'

¿Qué estoy haciendo mal aquí?

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

0

Se espera que el reductor devuelva el acumulador:

 const order = { apple: 5, banana: 5, orange: 5 }; const indices = Object.keys(order).reduce( (previousValue, currentValue, currentIndex) => { previousValue[currentValue] = currentIndex; return previousValue; // <-- this was missing in your attempt. }, {} ); console.log(indices);

about 4 years ago · Juan Pablo Isaza Report

0

const order = { apple: 5, banana: 5, orange: 5, }; const mapByIndex = (obj) => { return Object.keys(obj).reduce((acc, curr, i) => { return { ...acc, [curr]: i, }; }, {}); }; console.log(mapByIndex(order)); // -> { apple: 0, banana: 1, orange: 2 }
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!