首页 > 解决方案 > 如何替换嵌套对象中的键

问题描述

我有一个这样的对象,

{
  id: '1',
  displaName: 'A',
  children: [
  {
    id: '2',
    displayName: 'B',
    children: [
    {
      id: '3',
      displayName: 'C',
      children: [
            //More nested array here
      ]
    }
    ]
  }]
}

我只想更改密钥displayNamelabel以便我的对象看起来像这样,

{
  id: '1',
  label: 'A',  //change key displayName => label
  children: [
  {
    id: '2',
    label: 'B',  //change key displayName => label
    children: [
    {
      id: '3',
      label: 'C',  //change key displayName => label
      children: [
            //More nested array here
      ]
    }
    ]
  }]
}

我已经尝试过了,但无法替换嵌套数组中的键,

const newKeys = { displaName: "label"};
const renamedObj = renameKeys(resp.data, newKeys);
console.log(renamedObj);

function renameKeys(obj, newKeys) {
  const keyValues = Object.keys(obj).map(key => {
    console.log(key);
    let newKey = null
    if(key === 'displayName'){
       newKey = 'label'
    }else{
       newKey = key
    }
    console.log(newKey);
    return { [newKey]: obj[key] };
  });
  return Object.assign({}, ...keyValues);
}

请帮我解决这个问题。

提前致谢。

标签: javascriptjavascript-objects

解决方案


  1. 您的代码中有错字。一些变量显示为displaName而不是 displayName

  2. 您需要递归调用函数才能按预期工作。

  3. 您没有使用newKeys变量进行重命名。您只是将其硬编码为newKey = 'label'. 但这个问题与问题无关。

const resp = {
  data: {
    id: '1',
    displayName: 'A',
    children: [{
      id: '2',
      displayName: 'B',
      children: [{
        id: '3',
        displayName: 'C',
        children: [
          //More nested array here
        ]
      }]
    }]
  }
}

const newKeys = {
  displayName: "label"
};
const renamedObj = this.renameKeys(resp.data, newKeys);
console.log(renamedObj);

function renameKeys(obj, newKeys) {
  const keyValues = Object.keys(obj).map(key => {
    let newKey = null
    if (key === 'displayName') {
      newKey = newKeys.displayName
    } else {
      newKey = key
    }
    if (key === 'children') {
      obj[key] = obj[key].map(obj => renameKeys(obj, newKeys));    
    }
    return {
      [newKey]: obj[key]
    };
  });
  return Object.assign({}, ...keyValues);
}


推荐阅读