0

I am trying to rename some of the properties on a series of objects in an array in order, but I only want to change the name to some of the properties and not having to rebuild the whole object to maintain the same order.

const data = [
  {
    prop1: 'Change key but keep position',
    second: 'Keep same key name and position',
    prop3: 'Change key but keep position',
    fourth: 'Keep same key name and position',
  }
]

const res = data.map(({prop1, prop3, ...obj}) => ({
  first: prop1,
  third: prop3,
  ...obj,
}))


console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Desired output

[
 {
   first: 'Change key but keep position',
   second: 'Keep same key name and position',
   third: 'Change key but keep position',
   fourth: 'Keep same key name and position'
 }
]
Álvaro
  • 2,255
  • 1
  • 22
  • 48
  • What's the problem? – Spectric Aug 15 '21 at 15:16
  • I need it to be `first, second, third and fourth` but I don't know how, without rebuildiung the entire object – Álvaro Aug 15 '21 at 15:17
  • 2
    The order of object keys are not guaranteed. Therefore relying on them seems bad practice. This thread might help: https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Harun Yilmaz Aug 15 '21 at 15:18
  • 1
    Does this answer your question? [JS rename an object key, while preserving its position in the object](https://stackoverflow.com/questions/48082071/js-rename-an-object-key-while-preserving-its-position-in-the-object) – Heretic Monkey Aug 15 '21 at 15:22
  • It does work for one property but I want to change several – Álvaro Aug 15 '21 at 15:42
  • The only reason to care about the property order is if you are iterating these objects with `for (x in obj)` (or `for..of`). Most modern use of objects to display data either involves a template, where each object property is inserted into the right place, and the template is how order is maintained, or an array of keys, like `['first', 'second', 'fourth', 'third'].map(x => obj[x])` – James Aug 15 '21 at 15:54
  • That's all well and good, but can you order this array of objects without having to rebuild the entire object? – Álvaro Aug 15 '21 at 15:57
  • 1
    Don't rely on property order in objects. – James Aug 15 '21 at 15:58

1 Answers1

2

Maybe something like this:

const data = [
  {
    prop1: 'Change key but keep position',
    second: 'Keep same key name and position',
    prop3: 'Change key but keep position',
    fourth: 'Keep same key name and position',
  }
];

const renameMap = { prop1: 'first', prop3: 'third'};

const res = data.map(
  obj => Object.fromEntries(Object.entries(obj).map(
    ([key, value]) => [renameMap[key] ?? key, value]
  ))
);

console.log(res);
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26