如何为长度不均的对象数组填充null/未定义值
如何为对象数组填充null值以统一数组长度?
我需要迭代代码在表格展示数据,要求所有对象的contacts数组长度一致,短的数组要为对应键填充null值,让数组长度统一。
原始JSON
[ { "toolName": "Alteryx", "contacts": [ { "contactPerson": "James clear", "email": "james@google.com" }, { "contactPerson": "Paul Unger", "email": "paulunger@twitter.com" } ] }, { "toolName": "Processes", "contacts": [ { "contactPerson": "naomi Unger", "email": "naomiunger@twitter.com" } ] }, { "toolName": "Alteryx Server", "contacts": [ { "contactPerson": "Avinash", "email": "avinash@meta.com" }, { "contactPerson": "Sowmia", "email": "sowmia@energy.com" } ] } ]
期望JSON
[ { "toolName": "Alteryx", "contacts": [ { "contactPerson": "James clear", "email": "james@google.com" }, { "contactPerson": "Paul Unger", "email": "paulunger@twitter.com" } ] }, { "toolName": "Processes", "contacts": [ { "contactPerson": "naomi Unger", "email": "naomiunger@twitter.com" }, { "contactPerson": null, "email": null } ] }, { "toolName": "Alteryx Server", "contacts": [ { "contactPerson": "Avinash", "email": "avinash@meta.com" }, { "contactPerson": "Sowmia", "email": "sowmia@energy.com" } ] } ]
之前尝试的无效代码
let max = 0; const masterArray = res?.data?.tools?.map((obj) => { obj.contacts.forEach((ele, ind) => { if(max <= ind){ max = ind; } for(let i = 0 ; i< max; i++){ if (ele !== undefined) return ele; return { ...ele, contactPerson: '', email: '', } } }); });
问题分析
你之前的代码逻辑存在几个核心问题:
map函数内没有返回处理后的对象,最终masterArray会全是undefinedforEach里的return无法终止外层逻辑,也不会修改原数组内容- 最大长度的计算时机错误,应该先遍历所有数组算出最大值,再统一补全
解决方案
分两步处理即可:
- 先算出所有
contacts数组的最大长度 - 遍历每个工具对象,将其
contacts数组补全到最大长度,缺的位置用{contactPerson: null, email: null}填充
完整代码如下:
// 假设你的数据源是res.data.tools const tools = res?.data?.tools || []; // 第一步:获取所有contacts数组的最大长度 const maxContactsLength = Math.max(...tools.map(tool => tool.contacts.length)); // 第二步:补全每个tool的contacts数组 const formattedTools = tools.map(tool => { // 复制原数组,避免修改原始数据 const updatedContacts = [...tool.contacts]; // 计算需要补充的空对象数量 const needAddCount = maxContactsLength - updatedContacts.length; // 循环补充指定数量的空对象 for (let i = 0; i < needAddCount; i++) { updatedContacts.push({ contactPerson: null, email: null }); } // 返回新的工具对象,保证原数据不变 return { ...tool, contacts: updatedContacts }; }); console.log(formattedTools);
代码说明
- 用
Math.max(...tools.map(...))快速获取最大长度,写法简洁高效 - 使用扩展运算符
...复制原数组和对象,避免直接修改原始数据,保证数据不可变性 - 通过循环补充对应数量的空对象,确保所有
contacts数组长度完全一致
内容的提问来源于stack exchange,提问作者Manny_s
相关产品推荐
相关产品推荐

