我有一个对象数组,例如:
var elements = [
{
LabCode: 'VA',
Zscore: 0.5,
Standard: 'std1'
},
{
LabCode: 'RE',
Zscore: 0.53,
Standard: 'std1'
},
{
LabCode: 'VO',
Zscore: 1.5,
Standard: 'std1'
},
{
LabCode: 'VA',
Zscore: 3.4,
Standard: 'std2'
},
{
LabCode: 'RE',
Zscore: 2.45,
Standard: 'std2'
},
{
LabCode: 'VO',
Zscore: 1.67,
Standard: 'std2'
}
]
我需要的是这个
var result = [
{
Standard: 'std1',
VA: 0.5,
RE: 0.53,
VO: 1.5
},
{
Standard: 'std2',
VA: 3.4,
RE: 2.45,
VO: 1.67
}
]
Labcode是动态的,因此我需要能够动态创建结果对象。我可以有很多标准,它们也是动态的。
我正在使用lodash。
请注意,属性名称必须反映实验室代码也是动态的这一事实。您记录为重复的答案中未解决此问题。
答案 0 :(得分:1)
您可以使用 reduce()
这样简单地完成此操作
var elements = [
{LabCode: 'VA',Zscore: 0.5, Standard: 'std1' },
{LabCode: 'RE',Zscore: 0.53,Standard: 'std1' },
{LabCode: 'VO',Zscore: 1.5, Standard: 'std1' },
{LabCode: 'VA',Zscore: 3.4, Standard: 'std2' },
{LabCode: 'RE',Zscore: 2.45,Standard: 'std2' },
{LabCode: 'VO',Zscore: 1.67,Standard: 'std2' }
]
let final = Object.values(elements.reduce((op,cur)=>{
if( op[cur['Standard']] ) {
op[cur['Standard']][cur['LabCode']] = cur['Zscore']
} else {
op[cur['Standard']] = {
'Standard' : cur['Standard'],
[cur['LabCode']]: cur['Zscore']
}
}
return op;
}, {} ))
console.log(final);
如果是IE,则可以使用它。
var elements = [
{LabCode: 'VA',Zscore: 0.5, Standard: 'std1' },
{LabCode: 'RE',Zscore: 0.53,Standard: 'std1' },
{LabCode: 'VO',Zscore: 1.5, Standard: 'std1' },
{LabCode: 'VA',Zscore: 3.4, Standard: 'std2' },
{LabCode: 'RE',Zscore: 2.45,Standard: 'std2' },
{LabCode: 'VO',Zscore: 1.67,Standard: 'std2' }
]
let final = elements.reduce((op,cur)=>{
if( op[cur['Standard']] ) {
op[cur['Standard']][cur['LabCode']] = cur['Zscore']
} else {
op[cur['Standard']] = {
'Standard' : cur['Standard'],
[cur['LabCode']]: cur['Zscore']
}
}
return op;
}, {} )
let finalop = [];
for(let key in final){
finalop.push(final[key])
}
console.log(finalop);
答案 1 :(得分:0)
您可以通过一个Array.reduce
和一些ES6(不带破折号)来完成此操作:
var data = [{ LabCode: 'VA', Zscore: 0.5, Standard: 'std1' }, { LabCode: 'RE', Zscore: 0.53, Standard: 'std1' }, { LabCode: 'VO', Zscore: 1.5, Standard: 'std1' }, { LabCode: 'VA', Zscore: 3.4, Standard: 'std2' }, { LabCode: 'RE', Zscore: 2.45, Standard: 'std2' }, { LabCode: 'VO', Zscore: 1.67, Standard: 'std2' } ]
const result = data.reduce((r, {LabCode, Zscore, Standard}, i, a) => {
r[Standard] = r[Standard] || {}
r[Standard][LabCode] = Zscore
return i == a.length-1 ? Object.keys(r).map(k => ({Standard: k, ...r[k]})) : r
}, {})
console.log(result)