如何在JavaScript中动态重命名对象嵌套数组中的对象键

问题描述 投票:0回答:1

我需要在对象JavaScript的嵌套数组中动态重命名对象键名,我已经尝试过使用此代码。这也是我仅从Stack Overflow获得的,但这无法正常工作,这意味着它仅在不进行深度替换的情况下检查第一级。

const node = {
  'id': 'de603a3e',
  'name': 'erewr',
  'subGroups': [
     {
        'id': '83d7c7e4',
        'name': 'dfds',
        'subGroups': [ ]
     },
     {
        'id': '050cde96',
        'name': 'tetwet',
        'subGroups': [ ]
     },
     {
        'id': 'd67cc4e8',
        'name': 'wewqe',
        'subGroups': [
           {
              'id': '553c301d',
              'name': 'ewqe',
              'subGroups': [

              ]
           }
        ]
     },
     {
        'id': '5d5ae5f2',
        'name': 'rwq',
        'subGroups': [
           {
              'id': 'ff29ad54',
              'name': 'wqe',
              'subGroups': [

              ]
           },
           {
              'id': '5d013943',
              'name': 'weqe',
              'subGroups': [

              ]
           }
        ]
     }
  ]
}

console.log(renameKey(node, { subGroups: 'subordinates' }))

renameKey(obj, keysMap) { 
    return transform(obj, function(result, value, key) { 
      const currentKey = keysMap[key] || key; 
      result[currentKey] = isObject(value) ? this.renameKey(value, keysMap) : value; 
    });
  }

我正在TypeScript中使用此代码。notetransformisObject是破折号

我收到错误ERROR TypeError: Cannot read property 'replaceKeysDeep' of undefined

javascript typescript lodash
1个回答
0
投票

const node = {
  'id': 'de603a3e',
  'name': 'erewr',
  'subGroups': [
     {
        'id': '83d7c7e4',
        'name': 'dfds',
        'subGroups': [ ]
     },
     {
        'id': '050cde96',
        'name': 'tetwet',
        'subGroups': [ ]
     },
     {
        'id': 'd67cc4e8',
        'name': 'wewqe',
        'subGroups': [
           {
              'id': '553c301d',
              'name': 'ewqe',
              'subGroups': [

              ]
           }
        ]
     },
     {
        'id': '5d5ae5f2',
        'name': 'rwq',
        'subGroups': [
           {
              'id': 'ff29ad54',
              'name': 'wqe',
              'subGroups': [

              ]
           },
           {
              'id': '5d013943',
              'name': 'weqe',
              'subGroups': [

              ]
           }
        ]
     }
  ]
}

console.log(renameKey(node, { subGroups: 'subordinates' }))

function renameKey(obj, keysMap) { 
    return _.transform(obj, function(result, value, key) { 
      const currentKey = keysMap[key] || key; 
      result[currentKey] = _.isObject(value) ? renameKey(value, keysMap) : value; 
    });
  }
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.