我有一个相当大的javascript对象(即50个键),我从API检索并希望将变量命名约定重新映射到我们的代码变量约定。目前,我这样做:
let newObject = {
myVar1: response.MyVar1,
myVar2: response.MyVar2
//...etc
是否有一个干净的(即没有Regexp
),使用lodash
或其他方法做到这一点的简单方法?我真的很喜欢_.renameKeys(response, "camelCase")
答案 0 :(得分:1)
Lodash通过结合_.mapKeys
和_.camelCase
方法提供了一种方便的方法:
const obj = {
MyVar1: "foo",
my_var_2: "bar",
["my-var-3"]: "baz",
}
console.log(_.mapKeys(obj, (v, k) => _.camelCase(k)))

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
&#13;
答案 1 :(得分:0)
const newObject = Object.keys(oldObject).reduce(function(accumulator, key){
const newKey = transformKey(key);
accumulator[newKey] = oldObject[key];
return accumulator;
}, {});
function transformKey(key) {
//whatever you need to do to convert the key format
}