banguncool
banguncool

Reputation: 47

Insert Object to Array getting problem with access it (Nodejs)

sorry for my bad English. I have weird problem when insert object to array then access it again.

Here is my code:

let content = new Array()
let dataDefault = {
  frame: 0, 
  time_running: 0,
  status: 'not_available', 

  precast_id: ['', ''],
  product_type: ['', ''],
  project: ['', ''],
  mold_number: -1,
  weight: {
    ra: -1,
    ri: -1
  },
  batch_id: [],

  start: 0,
  stop: 0,
  code: ['', ''],
  mix_design: ['', ''],
  operator: '',
  note: '',
  auto: false,
  quality: '' 
}

for (let i = 0; i < 2; i++) {
  content[i] = dataDefault
  content[i].frame = i    // it should be 0, and 1  <<--------------
}

// result content.frame = 1 in array [0, 1]
console.log(content)

I insert object into content array, then edit "frame" collection. It should be each array has different number of frame because of for loop. But I've got the same result on frame collection.

Here is the result:

[ { frame: 1,  // <<-------------------- same
    time_running: 0,
    status: 'not_available',
    precast_id: [ '', '' ],
    product_type: [ '', '' ],
    project: [ '', '' ],
    mold_number: -1,
    weight: { ra: -1, ri: -1 },
    batch_id: [],
    start: 0,
    stop: 0,
    code: [ '', '' ],
    mix_design: [ '', '' ],
    operator: '',
    note: '',
    auto: false,
    quality: '' },
  { frame: 1,  // <<-------------------- same
    time_running: 0,
    status: 'not_available',
    precast_id: [ '', '' ],
    product_type: [ '', '' ],
    project: [ '', '' ],
    mold_number: -1,
    weight: { ra: -1, ri: -1 },
    batch_id: [],
    start: 0,
    stop: 0,
    code: [ '', '' ],
    mix_design: [ '', '' ],
    operator: '',
    note: '',
    auto: false,
    quality: '' } ]

Where I did wrong? Hope you guys can help me, Thank you in advance.

Upvotes: 1

Views: 74

Answers (2)

Maruth51
Maruth51

Reputation: 36

as you are referring same object you got the same result. in simple create new object and append in array

for (let i = 0; i < 2; i++) {
  content[i] = {...dataDefault} // ES6 object de-structure 
  content[i].frame = i  

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You need to create a new copy of object for each index, instead of adding reference of same object,

A simple way is to create a function which returns an object

let content = new Array()
let dataDefault = () => ({
  frame: 0, 
  time_running: 0,
  status: 'not_available', 
  precast_id: ['', ''],
  product_type: ['', ''],
  project: ['', ''],
  mold_number: -1,
  weight: {
    ra: -1,
    ri: -1
  },
  batch_id: [],

  start: 0,
  stop: 0,
  code: ['', ''],
  mix_design: ['', ''],
  operator: '',
  note: '',
  auto: false,
  quality: '' 
})

for (let i = 0; i < 2; i++) {
  content[i] = dataDefault()
  content[i].frame = i
}

console.log(content)

Upvotes: 1

Related Questions