【问题标题】:java script rename the attribute name in array of tree objectsjava脚本重命名树对象数组中的属性名称
【发布时间】:2021-01-22 06:46:46
【问题描述】:

我需要在所有对象(父对象和子对象)中用“名称”重命名“文本”属性 API 返回的对象如下:

"content": [
  [{
    "id": 1,
    "text": "hierarchy 1",
    "icon": "h",
    "children": [{
        "id": 2,
        "text": "hierarchy 11",
        "icon": "h",
        "children": []
      },
      {
        "id": 3,
        "text": "hierarchy 110",
        "icon": "h",
        "children": []
      }
    ]
  }]
]

我的 API 函数应该返回相同的结果,但在将“text”重命名为“name”之后:

  async getTree() {
    const res = await axios.get("/api/HierarchyTree");
    return res.data.content["0"].map(item => {
      return {
        ...item,
        name: item.text
      };
    });

  }

结果应该是:

"content": [

  {
    "id": 1,
    "name": "hierarchy 1",
    "icon": "h",
    "children": [{
        "id": 2,
        "name": "hierarchy 11",
        "icon": "h",
        "children": []
      },
      {
        "id": 3,
        "name": "hierarchy 110",
        "icon": "h",
        "children": []
      }
    ]
  }
]

【问题讨论】:

  • 欢迎来到 Stack Overflow!请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题,然后试一试. 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。

标签: javascript json vue.js axios


【解决方案1】:

也许是这个?

let  content = [
  [{
    "id": 1,
    "text": "hierarchy 1",
    "icon": "h",
    "children": [{
        "id": 2,
        "text": "hierarchy 11",
        "icon": "h",
        "children": []
      },
      {
        "id": 3,
        "text": "hierarchy 110",
        "icon": "h",
        "children": []
      }
    ]
  }]
]
content = JSON.parse(JSON.stringify(content[0]).replace(/"text"/g,'"name"'))
console.log(content)

【讨论】:

    猜你喜欢
    • 2020-04-19
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 2021-10-30
    • 2017-12-11
    • 1970-01-01
    相关资源
    最近更新 更多