目录

修改后端返回的json树形数据的字段名

修改后端返回的json树形数据的字段名

https://img-home.csdnimg.cn/images/20240715101418.png

关键词由CSDN通过智能技术生成

有时候后端返回的数据字段名不是我们想要的,这时就可以通过JSON.parse和JSON.stringify进行修改

1.后端返回的数据

 data: [
        {
          title: "江西",
          id: 1,
          children: [
            {
              title: "南昌",
              id: 1000,
              children: [
                {
                  title: "青山湖区",
                  id: 10001
                },
                {
                  title: "高新区",
                  id: 10002
                }
              ]
            },
            {
              title: "九江",
              id: 1001
            },
            {
              title: "赣州",
              id: 1002
            }
          ]
        }
]

2.把title这个字段名改为name

this.data = JSON.parse(JSON.stringify(this.data).replace(/"title"/g,'"name"'))

3.这样我们就能得到我们想要的字段名了

data: [
        {
          name: "江西",
          id: 1,
          children: [
            {
              name: "南昌",
              id: 1000,
              children: [
                {
                  name: "青山湖区",
                  id: 10001
                },
                {
                  name: "高新区",
                  id: 10002
                }
              ]
            },
            {
              name: "九江",
              id: 1001
            },
            {
              name: "赣州",
              id: 1002
            }
          ]
        }
]