如何将指定数组转换为含唯一key且存储多value的JavaScript对象
将JavaScript数组转换为按type分组的对象
问题说明
给定如下JavaScript数组:
var data = [{type: 'physical', value: 'verified'}, {type: 'reference', value: 'owner'}, {type: 'physical', value: 'pending'}, {type: 'document', value: 'pending'} ]
需将其转换为以type为唯一键、对应值为该type下所有value组成的数组的对象,预期结果如下:
var result = { physical: ['verified', 'pending'], reference: ['owner'], document: ['pending'] }
实现方法
方法1:使用Array.prototype.reduce()
这是JavaScript中处理数组分组的常用方案,通过遍历数组逐步构建目标对象:
const data = [{type: 'physical', value: 'verified'}, {type: 'reference', value: 'owner'}, {type: 'physical', value: 'pending'}, {type: 'document', value: 'pending'} ]; const groupedData = data.reduce((acc, item) => { // 若当前type未在累加对象中,初始化空数组 if (!acc[item.type]) { acc[item.type] = []; } // 将当前value推入对应type的数组 acc[item.type].push(item.value); return acc; }, {}); console.log(groupedData);
方法2:使用for...of循环
如果觉得reduce逻辑不够直观,可采用普通循环实现,逻辑更直白:
const data = [{type: 'physical', value: 'verified'}, {type: 'reference', value: 'owner'}, {type: 'physical', value: 'pending'}, {type: 'document', value: 'pending'} ]; const groupedData = {}; for (const item of data) { if (!groupedData[item.type]) { groupedData[item.type] = []; } groupedData[item.type].push(item.value); } console.log(groupedData);
方法3:使用Map辅助分组
先用Map存储分组关系,再转换为普通对象,适合需要对分组结果进行后续操作的场景:
const data = [{type: 'physical', value: 'verified'}, {type: 'reference', value: 'owner'}, {type: 'physical', value: 'pending'}, {type: 'document', value: 'pending'} ]; const map = new Map(); data.forEach(item => { if (!map.has(item.type)) { map.set(item.type, []); } map.get(item.type).push(item.value); }); // 将Map转换为普通对象 const groupedData = Object.fromEntries(map); console.log(groupedData);
内容的提问来源于stack exchange,提问作者raghav kumar
相关产品推荐
相关产品推荐

