Node.js中合并数组内JSON对象及正确迭代方法咨询
数组对象合并问题及解决方案
问题背景
调用fileImport函数返回一个包含两个JSON对象的数组,代码及返回结果如下:
return new Promise((resolve) => { fileImport(userImport) .then ((response) => { console.log(response); resolve(response); }) })
返回结果:
[ { users: [ [Object], [Object], [Object], [Object] ], errors: [] }, { users: [ [Object], [Object], [Object], [Object] ], errors: [] } ]
尝试用for...in遍历数组时,输出结果为0和1,不清楚其来源,需要将两个对象合并为单个JSON对象。
问题解释
0和1是数组的索引。数组在JavaScript中本质是特殊的对象,索引就是它的可枚举属性键,for...in会遍历对象的所有可枚举属性,所以会输出数组元素的索引值。遍历数组应该使用更合适的方式,比如for...of、普通for循环或数组内置方法。
合并方案
方案一:使用数组reduce方法(推荐)
通过reduce累加数组中的每个对象,合并users和errors数组:
const mergedResult = response.reduce((accumulator, currentItem) => { return { users: [...accumulator.users, ...currentItem.users], errors: [...accumulator.errors, ...currentItem.errors] }; }, { users: [], errors: [] }); // 初始值为包含空数组的对象
方案二:手动遍历(for...of)
用for...of遍历数组元素,逐个合并数组内容:
const mergedResult = { users: [], errors: [] }; for (const item of response) { // 扩展运算符将当前item的users和errors元素推入合并后的数组 mergedResult.users.push(...item.users); mergedResult.errors.push(...item.errors); }
两种方案最终都会得到一个合并后的对象:
{ users: [/* 所有合并后的用户对象 */], errors: [/* 所有合并后的错误信息 */] }
内容的提问来源于stack exchange,提问作者Nimrod Yanai
相关产品推荐
相关产品推荐

