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

125
Views
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 answers
Answer question

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 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!