'Objects overwrite another object even when I make a new copy of the Object?
I have this function that rewrites a array of objects to a more gathered piece and does filtering. But the problem is that for both "id"/regNum it just ends up returning the same values even though they are clearly different. I have tried to copy the object since I have a feeling the problems comes from it referencing it to the object but I have no clue. It is probably just one line that have to be changed? FsFiddle: https://jsfiddle.net/j4fw81ds/84/
function Test2(){
const filterObject = [{
gender: "male",
level: 2
}, {
gender: "male",
level: 1
}]
const startTestArray = [{
"value": 0,
"Time": "1983",
"gender": "male",
"level": 1,
"name": "Jonas",
"regNum": "5014"
},
{
"value": 0,
"Time": "1984",
"gender": "male",
"level": 2,
"name": "Jonas",
"regNum": "5014"
},
{
"value": 0,
"Time": "1985",
"gender": "male",
"level": 1,
"name": "Jonas",
"regNum": "5014"
},
{
"value": 0,
"Time": "1985",
"gender": "male",
"level": 2,
"name": "Jonas",
"regNum": "5014"
},
{
"value": 13.1,
"Time": "2016",
"gender": "male",
"level": 1,
"name": "Jonas",
"regNum": "1620",
},
{
"value": 13.6,
"Time": "2017",
"gender": "male",
"level": 2,
"name": "Frøya",
"regNum": "1620",
},
{
"value": 0,
"Time": "2018",
"gender": "male",
"level": 1,
"name": "Frøya",
"regNum": "1620",
},
]
const object = {
"male": {
1: null,
2: null
}
}
const unique = [...new Set(startTestArray.map(item => item.regNum))];
const newArray = []
unique.forEach((element) => {
const currArray = startTestArray.filter((e) => e.regNum === element);
const copynewNobject = {
...object
}
filterObject.forEach((filterElement) => {
const matching = currArray.filter((item) => Object.entries(filterElement).every(([key, value]) => item[key] === value))
copynewNobject[Object.values(filterElement)[0]][Object.values(filterElement)[1]] = Object.fromEntries(matching.map((item) => [item.Time, item.value]))
})
newArray.push({
reg: currArray[0].regNum,
name:currArray[0].name,
...copynewNobject
})
})
newArray.map((object)=>{
console.log(object.reg)
console.log(object.male)
})
}
/*Why does these return the same when values for regnum are different and the values for each is different but somehow the first values get overwritten? This should return
for 5014 it should return
{
male:
1:{
1983:0,
1985:0,
},
2:{
1984:0,
1985:0
}
}
and for 1620 it should return:
{
1: {
2016: 13.1,
2018: 0
},
2: {
2017: 13.6
}
}
but yet it returns that for both?
*/
Test2()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
