如何合并API返回的JSON对象并展开嵌套数组?
解决API返回数组合并为一维数组的问题
你遇到的嵌套数组问题,根源是d1和d2本身就是数组,直接调用push(d1, d2)会把这两个数组整体作为元素插入到combinedJson中,自然形成嵌套结构。以下是几种快速解决的方案:
方案一:用扩展运算符展开数组元素后push
修改then回调里的push逻辑,用...展开数组的每个元素,再添加到目标数组:
Promise.all([r1, r2]) .then(([d1, d2]) => { combinedJson.push(...d1, ...d2); console.log(combinedJson); }) .catch(error => { console.error(error); });
...d1会把d1数组中的每个元素单独提取出来,依次添加到combinedJson,d2同理,最终得到一维数组。
方案二:使用concat方法合并数组
concat方法会将传入的数组合并到原数组并返回新的一维数组,注意需要重新赋值给combinedJson:
Promise.all([r1, r2]) .then(([d1, d2]) => { combinedJson = combinedJson.concat(d1, d2); console.log(combinedJson); }) .catch(error => { console.error(error); });
方案三:直接合并结果数组(更简洁)
如果不需要提前保留空数组combinedJson的声明,可以直接在回调里合并两个数组:
Promise.all([r1, r2]) .then(([d1, d2]) => { const combinedJson = [...d1, ...d2]; console.log(combinedJson); }) .catch(error => { console.error(error); });
内容的提问来源于stack exchange,提问作者TJ Rustbucket
相关产品推荐
相关产品推荐

