lodash:重命名对象中的键

2 javascript object lodash

我想重命名obj中的键,由此:

objs = {
  one: { description: "value", amount: 5, value: { description: "value desc", identifier: "some text"} },
  two: { description: "value", amount: 5, value: { description: "value desc", identifier: "some text"} }
}
Run Code Online (Sandbox Code Playgroud)

进入这个:

objs = {
  one: { original_description: "value", amount: 5, value: { description: "value desc", identifier: "some text"} },
  two: { original_description: "value", amount: 5, value: { description: "value desc", identifier: "some text"} }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ess 8

你真的不需要lodash.您需要做的是使用旧值在对象上创建一个新键,然后删除旧键.例如:

Object.keys(objs).forEach(function (key) {
    objs[key].original_description = objs[key].description;
    delete objs[key].description;
});
Run Code Online (Sandbox Code Playgroud)

如果您不熟悉该delete运算符,请参阅MDN文档delete

  • 此方法正在改变原始对象,在此处找到使用 Lodash https://gist.github.com/LeoAref/9e34436c8b140d690733631befc248ba 的不可变版本 (6认同)