如何按ID将多级JavaScript数组转换为指定树形JSON结构?
问题:将两个JavaScript数组按ID关联转换为指定树形JSON对象
给定数组
let firstLevelArr = [ { id: '1', name: 'India' }, { id: '2', name: 'Germany' } ]; let secondLevelArr = [ { id: 's1', parentId: '2', name: 'Bavaria' }, { id: 's2', parentId: '2', name: 'Berlin' }, { id: 's3', parentId: '1', name: 'Maharashtra' }, { id: 's4', parentId: '1', name: 'Tamilnadu' } ];
期望输出格式
{ countries: { '01': { countryName: 'India', states: { s3: { stateName: 'Maharashtra' }, s4: { stateName: 'Tamilnadu' } } }, '02': { countryName: 'Germany', states: { s1: { stateName: 'Bavaria' }, s2: { stateName: 'Berlin' } } } } }
尝试的错误代码
const mergeArrays = (arr1 = [], arr2 = []) => { let res = []; res = arr1.map(obj => { const index = arr2.findIndex(el => el["parentId"] == obj["id"]); const filteredArr = arr2.filter((a, i) => a.parentId === obj.id); const state = index !== -1 ? filteredArr : []; return { ...obj, ...state }; }); console.log(res); return res; };
正确实现方法
你的代码问题在于返回数组结构,且直接展开州数组到对象中会导致格式错误。以下是符合要求的实现:
const convertToTree = (countries, states) => { // 按parentId分组州,提升后续查找效率 const stateGroups = states.reduce((groups, state) => { const parentId = state.parentId; if (!groups[parentId]) { groups[parentId] = []; } groups[parentId].push(state); return groups; }, {}); // 构建目标格式的countries对象 const countriesObj = countries.reduce((acc, country, index) => { // 生成两位数字的国家键,如"01""02" const countryKey = String(index + 1).padStart(2, '0'); // 获取当前国家对应的所有州 const countryStates = stateGroups[country.id] || []; // 将州转换为指定格式的对象 const statesObj = countryStates.reduce((stateAcc, state) => { stateAcc[state.id] = { stateName: state.name }; return stateAcc; }, {}); acc[countryKey] = { countryName: country.name, states: statesObj }; return acc; }, {}); return { countries: countriesObj }; }; // 调用示例 const result = convertToTree(firstLevelArr, secondLevelArr); console.log(result);
关键说明:
- 用
reduce对州数组按parentId分组,避免重复过滤数组,提升性能 - 通过
padStart(2, '0')将国家序号格式化为两位数字,匹配输出要求 - 每个州转换为以自身
id为键的对象,字段名统一改为stateName - 最终组装成外层包含
countries属性的目标结构
内容的提问来源于stack exchange,提问作者Dinesh Kumar
相关产品推荐
相关产品推荐

