I need to assign an object inside a loop. Here's my code :
let dataObj = {}
let dataArr = []
, temp = []
while ( i < file.length ) {
array[i].forEach(item => temp.push(item))
dataObj.name = temp[0]
dataObj.nim = temp[1]
dataArr.push(dataObj)
temp = []
i++
}
Expected output:
// dataArr = [{name: panji, nim: 123}, {name: gifary, nim: 234}]
Reality :
// dataArr = [{name: gifary, nim: 234}, {name: gifary, nim: 234}]
I'm not sure how can I do this right. Does anybody know the way?
Thank you for your help!
2 Answers 2
dataObj is a reference to the same object. You can do it without using a variable:
dataArr.push({
name: temp[0],
nim : temp[1]
})
1 Comment
You are facing reference problem. Object set by reference will cause same data when you push to array because its same object with different variable name
while ( i < file.length ) {
array[i].forEach(item => temp.push(item))
// use new object instead
let dataObj = {name: temp[0], nim: temp[1]};
dataArr.push(dataObj)
temp = []
i++
}
Create new object instead or clone your object using this
let newObj = JSON.parse(JSON.stringify(dataObj);
Comments
Explore related questions
See similar questions with these tags.
.mapinstead of something more appropriate like.forEach..forEachunshiftinstead ofpush