Rename the keys of a JavaScript object to have a sequential order

Let's assume that you have the following JavaScript object:

let orders = {

    0: 'Salad',
    1: 'Steak',
    3: 'Coca-Cola',
    4: 'Ice cream'


If you wanted to redefine the object so that the keys have a sequential order, you could use a Object.entries() and a Object.fromEntries() function.


// Returns array of sequential [key, value]
let sequential = Object.entries(orders).map(([key, value], index) => [index, value])

// Transform the array into an object
let sorted = Object.fromEntries(sequential)


/* {
    0: 'Salad', 
    1: 'Steak', 
    2: 'Coca-Cola', 
    3: 'Ice cream'
} */

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.