【vue】修改对象/数组属性键名
1、对象属性键名修改:
1 data: { 2 code: 0, 3 text: '数据分析', 4 plant: [], 5 }, 6 // 把data下的plant改成children 7 data: { 8 code: 0, 9 text: '数据分析', 10 children: [], 11 },
关键语句
1 let newData= JSON.parse(JSON.stringify(this.data).replace(/plant/g,"children"))
2、数组属性键名修改:
1 plant: [{ 2 plant_code: 1, 3 plant_name: "烘干车间", 4 device:[], 5 },{ 6 plant_code: 2, 7 plant_name: "窑炉车间", 8 device: Array(2), 9 }], 10 // 数组中属性键名挨个修改成所需 11 // 把plant下的plant_code改成company_id、plant_name改成company_name、device改成children 12 plant: [{ 13 company_id: 1, 14 company_name: "烘干车间", 15 children:[], 16 },{ 17 company_id: 2, 18 company_name: "窑炉车间", 19 children: Array(2), 20 }],
关键语句
1 this.plant = this.plant.map(item=>({ 2 company_id:item.children_code, 3 company_name:item.children_name, 4 children:item.device, 5 }))
现实需求
原始从后端获取到的数据:
1 res:{ 2 data: { 3 company_id: 1001 4 company_name: "包头稀土园区" 5 plant: [{ 6 plant_code: 1, 7 plant_name: "烘干车间", 8 device:[{ 9 collection_device_name: "1#电表", 10 collection_device_code: 1 11 },{ 12 collection_device_name: "2#电表", 13 collection_device_code: 2 14 },{ 15 collection_device_name: "3#电表", 16 collection_device_code: 3 17 }], 18 },{ 19 plant_code: 2, 20 plant_name: "窑炉车间", 21 device: Array(2), 22 }], 23 } 24 }
输出格式化,所有name变成company_name,所有叶子变成children:
1 res:{ 2 data: { 3 company_id: 1001 4 company_name: "包头稀土园区" 5 children: [{ 6 company_id: 1, 7 company_name: "烘干车间", 8 children:[{ 9 company_name: "1#电表", 10 company_id: 1 11 },{ 12 company_name: "2#电表", 13 company_id: 2 14 },{ 15 company_name: "3#电表", 16 company_id: 3 17 }], 18 },{ 19 company_id: 2, 20 company_name: "窑炉车间", 21 children: Array(2), 22 }], 23 } 24 }
关键语句
1 // plant改成children 2 let response = JSON.parse(JSON.stringify(res.data).replace(/plant/g,"children")) 3 // 车间中所有键名修改 4 if(response.children.length>0){ 5 response.children = response.children.map(item=>({ 6 company_id:item.children_code, 7 company_name:item.children_name, 8 children:item.device, 9 })) 10 for (const i in response.children) { 11 if (response.children.hasOwnProperty(i)) { 12 response.children[i].children = response.children[i].children.map(item=>({ 13 company_id:item.collection_device_code, 14 company_name:item.collection_device_name, 15 })) 16 } 17 } 18 } 19 console.log(response,'===');
此时的response已经是格式化好的了!