生成数组与代码预期不符求助:附数组需求及代码
Troubleshooting Your Array Mismatch Issue
Let's work through this problem together. First, I'll lay out the details you shared, then break down where your code might be going off-track and how to fix it.
Your Input Arrays
- Source array 1 (user IDs):
[201, 202, 203] - Source array 2 (user profiles):
[{username: "Luna", role: "editor"}, {username: "Kai", role: "admin"}, {username: "Zara", role: "viewer"}]
Expected Result Array
[ {id: 201, username: "Luna", role: "editor"}, {id: 202, username: "Kai", role: "admin"}, {id: 203, username: "Zara", role: "viewer"} ]
Your Current Code
function combineArrays(ids, profiles) { let output = []; ids.forEach(id => { profiles.forEach(profile => { output.push({id, ...profile}); }); }); return output; }
What's Causing the Mismatch?
Your nested forEach loops are pairing every ID with every profile object—so instead of 3 matching entries, you're getting 9 (3×3) entries, which is way off your expected structure.
Fixed Solution
Since your arrays are ordered (each ID corresponds to the profile at the same index), we can use map to iterate through both arrays in sync:
function combineArrays(ids, profiles) { return ids.map((id, index) => ({ id, ...profiles[index] })); }
Why This Works
maploops through theidsarray, and for each ID, we use theindexto grab the exact matching profile from the second array.- The spread operator (
...) merges theidproperty with the profile's properties, creating the exact object structure you need.
Quick Guard Clause (Optional)
If there's a chance your input arrays might be different lengths, add a check to avoid undefined values:
function combineArrays(ids, profiles) { if (ids.length !== profiles.length) { throw new Error("IDs and profiles arrays must have matching lengths"); } return ids.map((id, index) => ({ id, ...profiles[index] })); }
内容的提问来源于stack exchange,提问作者Jamshaid
相关产品推荐
相关产品推荐

