Javascript 中 ForEach 的替代箭头函数

Sri*_*thi 1 javascript arrays json arrow-functions

我有如下代码

function renameKey ( obj, oldKey, newKey ) {
  obj[newKey] = obj[oldKey];
  delete obj[oldKey];
}
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
Run Code Online (Sandbox Code Playgroud)

但似乎箭头函数 (=>) 在我的环境中不起作用并出现以下错误。

箭头函数语法 (=>)' 仅在 ES6 中可用(使用 'esversion: 6')

这是 Apigee 环境,我无权更改任何配置。当我删除箭头函数并像下面这样作为普通函数调用时,它失败了

const arr = JSON.parse(json);
arr.forEach(renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
Run Code Online (Sandbox Code Playgroud)

因此,为了更改 JSON 中的每个键,我如何使用 forEach 循环,或者如果有替代方法将会很有帮助。有人可以建议一下吗。

Nin*_*olz 5

如果你喜欢使用闭包

arr.forEach(renameKey('_id', 'id'))
Run Code Online (Sandbox Code Playgroud)

模式,您可以对旧的和新的键名进行闭包,并返回一个接受对象进行重命名的函数。

function renameKey (oldKey, newKey) {
    return function (obj) {
        obj[newKey] = obj[oldKey];
        delete obj[oldKey];
    };
}
Run Code Online (Sandbox Code Playgroud)