一. 需求
数组转对象
- 数组结构
List:[{id:1,code:'phone',value:'10101001'},{id:2,code:'name',value:'admin'},{id:3,code:'address',value:'XXXXXX'}
]
二. 数组转对象(键值对映射关系)
- 对象结构
object:{phone:'10101001',name:'admin',address:'XXXXXX'
}
2.1 Java端处理
@GetMapping("/getList")@ApiOperationSupport(order = 1)@ApiOperation(value = "详情", notes = "啥也不传")public R<Map<String, String>> getList() {List<DemoEntity> list = demoService.list();Map<String, String> collect = list.stream().collect(Collectors.toMap(DemoEntity::getCode, DemoEntity::getValue, (key1, key2) -> key1));return R.data(collect);}
2.2. Web端处理
2.2.1. Array.forEach()
let resultMap = {}
this.List.forEach((item) => {resultMap[item.code] = item.value
})
2.2.2 Array.map()
function listToMap(arr) {return this.List.reduce((resultMap, value, index) => {resultMap[item.code] = item.valuereturn resultMap;}, {});
}
2.2.3. for 循环
let resultMap = {}
for (let i = 0; i < this.List.length; i++) {resultMap[this.List[i].code] = this.List[i].value
}
三. 数组转 单个元素集合
- 对象结构
object:{phone:{{id:1,code:'phone',value:'10101001'}, },name:{{id:2,code:'name',value:'admin'},},address:{{id:3,code:'address',value:'XXXXXX'}}
}
3.1 Java端处理
@GetMapping("/getList")@ApiOperationSupport(order = 1)@ApiOperation(value = "获取单个元素集合", notes = "啥也不传")public R<Map<String, DemoEntity>> getList() {List<DemoEntity> list = demoService.list();Map<String, DemoEntity> collect = list.stream().collect(Collectors.toMap(DemoEntity::getCode, Function,identity(), (key1, key2) -> key1));return R.data(collect);}
3.2 Web端处理
3.2.1. Array.forEach()
let resultMap = {}
this.List.forEach((item) => {resultMap[item.code] = item
})
console.log(resultMap, 'resultMap')
3.2.2. for循环
// 传一个数组
function listToMap(arr) {let resultMap = {};for (let i = 0; i < arr.length; i++) {resultMap[arr[i].code] = arr[i];}return resultMap;
}