javascript - 如何替换嵌套对象中的键

标签 javascript javascript-objects

我有一个这样的对象,

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

我只想用 label 更改键 displayName 以便我的对象看起来像这样,

{
  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);
}

请帮我解决这个问题。

提前致谢。

最佳答案

  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);
}

关于javascript - 如何替换嵌套对象中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533695/

相关文章:

javascript - 如何在 python 中的 HTML 上运行 jquery 命令以进行 DOM 操作/抓取?

javascript - 如果 jquery 返回未定义并且不工作

javascript - JavaScript 对象历史记录如何将 URL 存储到其堆栈中?

javascript - 从对象内部的对象内部访问实例变量

javascript - (javascript) 在数组内的对象上调用方法

javascript - 这个生成的代码应该(打算)做什么?

javascript - 如何将数组索引拆分为该特定索引的 2 个索引

javascript - 函数调用正在为映射函数内的react js中的每个调用返回最后一个键

javascript - 如何在 Javascript 中正确更新购物车总计?

javascript - 为什么我不能使用函数作为 Map 的键?