lodash:重命名对象中的键

7

我希望将对象中的键重命名,从这个:

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"} }
}

转换为这样:

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"} }
}
1个回答

13

对于这个问题,你并不需要使用lodash。你需要做的是在对象上创建一个新的带有旧值的键,然后删除旧键。例如:

Object.keys(objs).forEach(function (key) {
    objs[key].original_description = objs[key].description;
    delete objs[key].description;
});
如果您不熟悉delete运算符,请参阅MDN文档中的delete

9
这种方法会改变原始对象,这里使用 Lodash 提供的不可变版本 https://gist.github.com/LeoAref/9e34436c8b140d690733631befc248ba - Muhammad Hamada

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接