使用Object.keys ES6更改对象键

Ala*_*hen 10 javascript ecmascript-6 reactjs

我有

var tab = {
abc:1,
def:40,
xyz: 50
}
Run Code Online (Sandbox Code Playgroud)

我想将abc,def,xyz的名称更改为其他内容,是否可能?

我试过了

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

console.log(test);
Run Code Online (Sandbox Code Playgroud)

我有很多未定义的键.

zvo*_*ona 7

以下是基于映射要替换的值的对象替换键的完整代码:

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] };
});
Run Code Online (Sandbox Code Playgroud)

这将输出一个包含三个对象的数组,其中键被替换.如果要从中创建新对象,只需:

const newTab = replacedItems.reduce((a, b) => Object.assign({}, a, b));
Run Code Online (Sandbox Code Playgroud)

这输出: {"a_b_c": 1, "d_e_f": 40, "xyz": 50}


Rav*_*ala 6

我是这样解决的。我使用映射来映射现有密钥和新密钥。只需用您需要的任何新值替换地图即可。最后使用从对象中删除旧的键omit

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

var map = {
    abc : "newabc",
    def : "newdef",
    xyz : "newxyz"
}


_.each(tab, function(value, key) {
    key = map[key] || key;
    tab[key] = value;
});


console.log(_.omit(tab, Object.keys(map)));
Run Code Online (Sandbox Code Playgroud)

  • 如果你不知道地图中的 abc 、 def 、 xyz 怎么办? (2认同)

Moh*_*ere 6

使用 lodash mapKeys函数可以很容易地转换对象键。

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

const map = {
  abc: "newabc",
  def: "newdef",
  xyz: "newxyz"
}

// Change keys
_.mapKeys(tab, (value, key) => {
  return map[value];
});

// -> { newabc: 1, newdef: 40, newxyz: 50 }
Run Code Online (Sandbox Code Playgroud)

  • 我认为应该是: return map[key] (3认同)

Cle*_*ens 5

这是一种通过解构赋值和箭头函数来实现的方法。

const rename = (({abc: a_b_c, ...rest}) => ({a_b_c, ...rest}))
console.log(rename({abc: 1, def: 2}))
// { "a_b_c": 1, "def": 2 }
Run Code Online (Sandbox Code Playgroud)