'browsed' is an array of objects with data for each letter:
[
{
allowMultiSign: undefined,
allowSingleSign: "1",
assignmentStatus: "Browsed",
disclaimer: null,
form16: false,
letterDate: "06-Mar-2020",
title: "letter02",
safetyLetterId: 987
},
{
allowMultiSign: undefined,
allowSingleSign: "1",
assignmentStatus: "Browsed",
disclaimer: null,
form16: false,
letterDate: "06-Mar-2020",
title: "letter01",
safetyLetterId: 123
},
{
allowMultiSign: undefined,
allowSingleSign: "1",
assignmentStatus: "Browsed",
disclaimer: null,
form16: false,
letterDate: "06-Mar-2020",
title: "letter03",
safetyLetterId: 456
},
{
allowMultiSign: undefined,
allowSingleSign: "1",
assignmentStatus: "Browsed",
disclaimer: null,
form16: false,
letterDate: "06-Mar-2020",
title: "letter04",
safetyLetterId: 789
}
]
I want to:
1 and 2 are working just fine (I've logged each step). The problem is with #3
when I log the final result -- multisign, I see only the last object. I'm expecting to see all 4 objects inside multisign.
I've used the spread operator before for this same exact task. I'm wondering if I'm just missing a small detail or if it's a compatibility issue. I am using javascript 6.9.0.
let multisign = {};
browsed.forEach(letter => {
if (letter.form16 == false && letter.allowMultiSign != false) {
let idAndTitle = {
safetyLetterId: letter.safetyLetterId,
title: letter.title
}
multisign = { ...multisign, ...idAndTitle }
}
});
console.log(multisign);
}
sample output
{
{
safetyLetterId: 789,
title: "letter04"
}
}
This is happening because when you spread an object with the same keys they get overridden see: multisign = { ...multisign, ...idAndTitle }
That's why the you only get the last one.
My suggestion would be either make multisign an array and push the objects into it or you have to transform the keys for idAndTitle
every object (maybe affix some index)
EDIT:
If you want to change the keys you have to change the idAndTitle
object
browsed.forEach((letter, index) => {
if (letter.form16 == false && letter.allowMultiSign != false) {
let idAndTitle = {
[`safetyLetterId${index}`]: letter.safetyLetterId,
[`title${index}`]: letter.title
}
...
Now the multisign object should look like this
{
{
safetyLetterId0: '...'
title0: '...'
},
{
safetyLetterId1: '...'
title1: '...'
},
...
}
And as you can see this kinda gets ugly so I would suggest to replace multisign with an array and push the new obj to it