0

I have some (potentially very large) array of objects like this:

[
 {
  'before1' => val,
  'same' => val,
  'before2' => val
 },
  ...
]

I need an efficient way to replace only some of the keys in the map (i.e. deleting keys won't work for me), and I have a map like this:

keyReplacements = {
 'before1' => 'after1',
 'same' => 'same',
 'before2' => 'after2'
}

I know the same => same is not necessary in the map, but it's helpful to include as a full translation schema.

Given this key mapping, what's an efficient method to replace my given array of objects with the following result?

[
 {
  'after1' => val,
  'same' => val,
  'after2' => val
 },
  ...
]

I've tried the following:

    static replaceObjectKeys(objectToReplace, keyMap) {
        objectToReplace.map(o =>
        Object.keys(o).map((key) => ({ [keyMap[key] || key]: o[key] })
        ).reduce((objectToReplace, b) => Object.assign({}, objectToReplace, b)))

        return objectToReplace
    }
    

But it just returns me the same object with nothing replaced

const newObject = this.replaceObjectKeys(oldObject, keyMap)
console.log("new obj: ", newObject) // this is the same as oldObject
return newObject
ShaneOH
  • 1,454
  • 1
  • 17
  • 29

2 Answers2

2

Here's a solution using entries:

const arr = [
 {
  'before1': 1,
  'same': 2,
  'before2': 3
 }, {
  'before1': 4,
  'same': 5,
 }, {
  'before1': 6,
  'before2': 7
 }, {
  'same': 8,
  'before2': 9
 },
];

const keyReplacements = {
 'before1': 'after1',
 'same': 'same',    // this is not necessary
 'before2': 'after2'
};

const newArr = arr.map(obj =>
  Object.fromEntries(Object.entries(obj).map(([k, v]) => [keyReplacements[k] || k, v]))
);

console.log(newArr);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
0

Use ES6 map()

arrayObj = arrayObj.map(item => {
  return {
    value: item.key1,
    key2: item.key2
  };
});