0

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!

asked Aug 3, 2019 at 11:32
4
  • 1
    You are not mapping an array. You are just misusing .map instead of something more appropriate like .forEach. Commented Aug 3, 2019 at 11:32
  • It gave the same result with .forEach Commented Aug 3, 2019 at 11:33
  • Can you show the initial array you're iterating over? Commented Aug 3, 2019 at 11:36
  • 1
    Well, what's your input? The output being wrong doesn't make sense unless we know what data you operate on. It might be that you are doing this in reverse and you might need to iterate backwards or unshift instead of push Commented Aug 3, 2019 at 11:37

2 Answers 2

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]
 })
answered Aug 3, 2019 at 11:36
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help, most probable reason would be a lack of information in the question, such as what is the input. So any answers would be considered guesswork till the question is more complete.
0

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);
answered Aug 3, 2019 at 11:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.