panji gemilang
panji gemilang

Reputation: 809

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!

Upvotes: 0

Views: 199

Answers (2)

William Gunawan
William Gunawan

Reputation: 750

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);

Upvotes: 0

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

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

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

Upvotes: 2

Related Questions