原始数组
const arr = [
{
'颜色': 'red',
'尺寸': '100',
'规格': 'aaa'
},
{
'颜色': 'blue',
'尺寸': '200',
'规格': 'aaa'
}
]
格式化后的数组
const array = [
{
'specificationName': '颜色',
'specificationValueList': [
{ 'specificationValue': 'red' },
{ 'specificationValue': 'blue' }
]
},
{
'specificationName': '尺寸',
'specificationValueList': [
{ 'specificationValue': '100' },
{ 'specificationValue': '200' }
]
},
{ 'specificationName': '规格',
'specificationValueList': [
{ 'specificationValue': 'aaa' }
]
}
]
实现
/**
* 数组归并
* @param targetJson 原始数组
* @param isUnique 是否去重
* @returns {Array} 归并的数组
*/
function parseJson(targetJson, isUnique) {
const map = {}
const arr = []
targetJson.forEach(item => {
// key:value 对象存储数据
for (const [key, value] of Object.entries(item)) {
if (!map[key]) {
map[key] = []
}
map[key].push(value)
}
})
// 对象转换为指定格式的数组
for (const [key, value] of Object.entries(map)) {
const obj = {
specificationName: key,
specificationValueList: []
}
// 是否去重
const uniqueValue = isUnique ? [...new Set(value)] : value
// 处理value的格式
uniqueValue.forEach(item => {
obj.specificationValueList.push({
specificationValue: item
})
})
arr.push(obj)
}
return arr
}
版权声明:本文为m0_37068028原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。