Ad

Mapping An Array Inside A Loop

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!

Ad

Answer

dataObj is a reference to the same object. You can do it without using a variable:

  dataArr.push({
     name: temp[0],
     nim : temp[1]
  })
Ad
source: stackoverflow.com
Ad