本篇文章是转载 附原文链接
转自 https://www.cnblogs.com/susu8/p/9817014.html
问题描述:
把list数组中相同的id合成一个,mat_qlt_id的值作为key, value作为值, 组成新数组newList
const list = [
{
sample_id: '1',
mat_qlt_id: 'M-015-4',
value: 3,
},
{
sample_id: '2',
mat_qlt_id: 'M-015-4',
value: 33,
},
{
sample_id: '1',
mat_qlt_id: 'M-015-5',
value: 2,
},
{
sample_id: '1',
mat_qlt_id: 'M-015-6',
value: 1,
},
{
sample_id: '2',
mat_qlt_id: 'M-015-5',
value: 22,
},
{
sample_id: '3',
mat_qlt_id: 'M-015-6',
value: 11,
},
{
sample_id: '2',
mat_qlt_id: 'M-015-6',
value: 11,
},
];
const newList = [];
list.forEach((data) => {
for (let i = 0; i < newList.length; i++) {
if (newList[i].sample_id === data.sample_id) {
newList[i][data.mat_qlt_id] = data.value;
return;
}
}
newList.push({
sample_id: data.sample_id,
[data.mat_qlt_id]: data.value,
});
});
console.log(newList);
转自 https://www.cnblogs.com/susu8/p/9817014.html