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
4
  • could you show us what you've tried ? Commented Aug 18, 2020 at 8:41
  • stackoverflow.com/a/45287523/5166758 Commented Aug 18, 2020 at 8:46
  • Does this answer your question? JavaScript: Object Rename Key Commented Aug 18, 2020 at 8:49
  • Edited the OP with an attempt I had earlier -- I could do this in PHP trivially but I'm not very familiar with Javascript/ES6 so I'm having a difficult time debugging the syntax and functions Commented Aug 18, 2020 at 8:51

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

Use ES6 map()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.