I'm having an issue where I want to use an existing array and update one of it's properties using a for loop. I expect the outer id and the id inside the array to match, so for example: a & a, b & b, c & c. However when I print out my final array, all of the inner ids are set to c.
I don't understand why this happens?
edit: added expected output
My Code
const accounts = [{
"id": 1,
"currency": "USD"
}];
const alphaId = ['a', 'b', 'c'];
let finalArr = [];
for (index in alphaId) {
let newAccount = {};
newAccount.id = alphaId[index];
newAccount.accounts = accounts;
newAccount.accounts.forEach(acc => {
acc.id = alphaId[index];
});
finalArr.push(newAccount);
}
Print Out
[
{
"id": "a",
"accounts": [
{
"id": "c",
"currency": "USD"
}
]
},
{
"id": "b",
"accounts": [
{
"id": "c",
"currency": "USD"
}
]
},
{
"id": "c",
"accounts": [
{
"id": "c",
"currency": "USD"
}
]
}
]
Expected Output
[
{
"id": "a",
"accounts": [
{
"id": "a",
"currency": "USD"
}
]
},
{
"id": "b",
"accounts": [
{
"id": "b",
"currency": "USD"
}
]
},
{
"id": "c",
"accounts": [
{
"id": "c",
"currency": "USD"
}
]
}
]