alex
alex

Reputation: 7601

Why are the following logs logging different values (array loop)?

What we want to do is to use a single schema create a new array (with the values of arrObj:

 const arrObj = [{
  id: 1,
  title: 'aaa'
}, {
  id: 2,
  title: 'bbb',
}]

const schema = [{
  name: 'id',
  value: ''
}, {
  name: 'title',
  value: ''
}]

const finalArrObj = []

arrObj.forEach(eachArrObj => {
  const eachArr = [...schema] // copy array without pointing to the original one
  eachArr.forEach(field => {
    field.value = eachArrObj[field.name]
    console.log('1: ' , field) // correct value
  })
  console.log('2: ', eachArr) // the objects are all the same
  console.log('3: ', eachArr[0].value) // the object here is correct
  finalArrObj.push(eachArr)
})

For some reason, the values in console log number 2 logs an array with the same object. Console log number 3 logs the correct object.

Why is this happening and how to fix it?

Live example: https://codepen.io/sky790312/pen/KmOgdy

UPDATE:

Desired result:

[{
  name: 'id',
  value: '1'
}, {
  name: 'title',
  value: 'aaa'
}],
[{
  name: 'id',
  value: '2'
}, {
  name: 'title',
  value: 'bbb'
}]

Upvotes: 1

Views: 52

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386746

You could map new objects by using Object.assign for schema, before assigning values to it.

schema.map(a => Object.assign({}, a, { value: o[a.name] }))
                ^^^^^^^^^^^^^^^^                            take empty object for
                                  ^                         assingning values of a and
                                     ^^^^^^^^^^^^^^^^^^^^   only the value of a property

const arrObj = [{ id: 1, title: 'aaa' }, { id: 2, title: 'bbb' }],
     schema = [{ name: 'id', value: '' }, { name: 'title', value: '' }],
     finalArrObj = arrObj.map(o => 
         schema.map(a => Object.assign({}, a, { value: o[a.name] }))
     );

console.log(finalArrObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Yordan Nikolov
Yordan Nikolov

Reputation: 2678

You have to copy the inner object also, replace this

const eachArr = [...schema];

with this

const eachArr = schema.map((e)=>{ 
   return Object.assign({}, e);
})

Upvotes: 1

Related Questions