How to reorganize JavaScript object keys based on specified array order

I’m working with a JavaScript object that has multiple properties:

{
  name: 'John',
  age: 25,
  city: 'Boston',
  country: 'USA'
}

I also have an array that defines the order I want for these object keys:

['city', 'age', 'name', 'country']

I need to restructure my object so the properties appear in the exact same sequence as specified in my array. The final result should look like this:

{
  city: 'Boston',
  age: 25,
  name: 'John',
  country: 'USA'
}

What’s the best approach to achieve this key reordering in JavaScript? I’ve tried a few methods but haven’t found a clean solution yet.

You can also use a simple loop to build the new object step by step. I use this when dealing with dynamic key orders from API responses:

const originalObj = {
  name: 'John',
  age: 25,
  city: 'Boston',
  country: 'USA'
};

const keyOrder = ['city', 'age', 'name', 'country'];
const reorderedObj = {};

for (const key of keyOrder) {
  if (originalObj.hasOwnProperty(key)) {
    reorderedObj[key] = originalObj[key];
  }
}

This gives you more control and lets you add conditional logic if needed. The hasOwnProperty check stops undefined values from getting added when keys don’t exist. Performance is about the same as other solutions, but it’s easier to modify later.

Had this exact problem a few months ago building a form component that needed consistent field ordering. Cleanest fix I found was Object.fromEntries() with map(). Here’s what worked:

const originalObj = {
  name: 'John',
  age: 25,
  city: 'Boston',
  country: 'USA'
};

const keyOrder = ['city', 'age', 'name', 'country'];

const reorderedObj = Object.fromEntries(
  keyOrder.map(key => [key, originalObj[key]])
);

Super straightforward and handles missing keys gracefully by setting them to undefined. I like it better than reduce methods - more readable and easier to debug. Just make sure your key order array has all the properties you need, or you’ll lose data from the original object.

you can also use reduce, which I think works really well here:

const reordered = keyOrder.reduce((acc, key) => {
  acc[key] = originalObj[key];
  return acc;
}, {});

works great and chains nicely with other operations. I’ve been using this approach a lot lately.