Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change object key using Object.keys ES6

I have

var tab = {
abc:1,
def:40,
xyz: 50
}

I want to change the name of abc,def, xyz to something else, is it possible?

I tried

const test = Object.keys(tab).map(key => {
  if (key === 'abc') {
    return [
      a_b_c: tab[key]
    ]
  }
});

console.log(test);

I got many undefined keys.

like image 252
Alan Jenshen Avatar asked May 08 '17 03:05

Alan Jenshen


1 Answers

Here is the full code for replacing keys based on object that maps the values to replace:

const tab = {abc: 1, def: 40, xyz: 50};
const replacements = {'abc': 'a_b_c', 'def': 'd_e_f'};

let replacedItems = Object.keys(tab).map((key) => {
  const newKey = replacements[key] || key;
  return { [newKey] : tab[key] };
});

This will output an array with three objects where keys are replaced. If you want to create a new object out of them, just:

const newTab = replacedItems.reduce((a, b) => Object.assign({}, a, b));

This outputs: {"a_b_c": 1, "d_e_f": 40, "xyz": 50}

like image 124
Samuli Hakoniemi Avatar answered Oct 20 '22 12:10

Samuli Hakoniemi