javascriptobjectproperties

How to rearrange object properties to the bottom of the property list?


This is a way to rearrange object properties to the top of the property list:

const raw = {
  a: 1,
  b: 2,
  // ...the rest
  y: 3,
  z: 4,
};

const templateTop = {
  y: null,
  z: null,
}

const rearrangedTop = Object.assign(templateTop, raw);
// {
//   y: 3,
//   z: 4,
//   a: 1,
//   b: 2,
//   ...the rest
// };

However, is there a way to rearrange some properties to the bottom? I.e.

const rearrangedBottom =  {
  // ...the rest
  y: 3,
  z: 4,
  a: 1,
  b: 2,
};

Solution

  • At first, don't depend on the order of an object. If the order is important to you, use an array. You can read this for more information. Does JavaScript guarantee object property order?

    If you still want to do this, destructuring is what you can give it a try. It still not a recommand way on a production.

    const {a, b, y, z, ...rest} = rearrangedTop
    // the a, b, y, z are the keys you want to rearrange.
    
    const rearrangedBottom = { ...rest, y, z, a, b}
    // the keys should be moved to the end.