Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
Reducing an array into an object in Javascript

I want to turn the following object

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

into the following object, with each key being assigned its index in the object as its value

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

This is the code I have but it's not working and I don't know why.

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

What am I doing wrong here?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Reducer is expected to return the accumulator:

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda