How to deeply map object keys with JavaScript (lodash)?

前端 未结 5 663
刺人心
刺人心 2021-02-02 12:48

https://lodash.com/docs#mapKeys

Is it possible to map an Object\'s keys deeply using Lodash? If not, is there another library providing this functionality (if grouped wi

5条回答
  •  花落未央
    2021-02-02 13:15

    Not a best one as per performance efficiency, but If you want to skip recursion part from your side and want to keep the code clean and simple then you can stringify it to json and use JSON.parse with additional parameter (callback) and there you can transform the keys with lodash.

    JSON.parse(JSON.stringify(obj), (k, v) => _.isObject(v) ? _.mapKeys(v, (_v, _k) => _k + '_hi') : v)
    

    Here is an working example:

    let obj = { a: 2, b: { c: 2, d: { a: 3 } } };
    let mappedObj = JSON.parse(JSON.stringify(obj), (k, v) => _.isObject(v) ? _.mapKeys(v, (_v, _k) => _k + '_hi') : v)
    console.log(mappedObj)

提交回复
热议问题