1 回答
TA贡献1848条经验 获得超2个赞
let data = [{
baySize: {
type: "integer",
value: "180"
},
bayAge: {
type: "integer",
value: "20"
},
totalBays: {
type: "integer",
value: "30"
},
bayType: {
type: "string",
value: "Brown"
},
sprayed: {
type: "boolean",
value: "No"
}
},
{
baySize: {
type: "integer",
value: "120"
},
bayAge: {
type: "integer",
value: "30"
},
totalBays: {
type: "integer",
value: "30"
},
bayType: {
type: "string",
value: "Grey"
},
sprayed: {
type: "boolean",
value: "No"
}
}
]
const intResult = {}
const strResult = {}
data.forEach(item => {
Object.keys(item).forEach(key => {
const innerItem = item[key]
if (innerItem.type === 'integer') {
if (!intResult.hasOwnProperty(key)) {
intResult[key] = {
count: 1,
value: +innerItem.value
}
} else {
intResult[key].count++
intResult[key].value += (+innerItem.value)
}
} else {
if (!strResult.hasOwnProperty(key)) {
strResult[key] = {}
}
if (!strResult[key].hasOwnProperty(innerItem.value)) {
strResult[key][innerItem.value] = 1
} else {
strResult[key][innerItem.value]++
}
}
})
})
const resultObj = {}
Object.keys(intResult).forEach(key => {
resultObj[key] = {
type: 'integer',
value: intResult[key].value / intResult[key].count + ''
}
})
Object.keys(strResult).forEach(key => {
let value = ''
Object.keys(strResult[key]).forEach(subKey => {
value += `${subKey}(${strResult[key][subKey]})`
})
resultObj[key] = {
type: 'string',
value
}
})
console.log(resultObj)
添加回答
举报