0
let arr = [];

let obj {case:''};

after I did below code twice,

arr.push(obj)

I got arr below

[{…}, {…}]
0: {case: ''}case: 
1: {case: ''}
length: 2[[Prototype]]: Array(0)

and I just want to push certain value (ex. 'a') in first object.

so, I did below code

arr[0].case = 'a'

but, second object is also changed like below

(2) [{…}, {…}]
0: {case: 2}
1: {case: 2}

So, I want to know how to push certain value in certain object in an array.

  • Please don't directly copy the output from your console into the question, it doesn't format very well. Instead, log the stringified results and copy those to your question. For example `console.log(JSON.stringify(arr, null, 2))` – Phil Nov 18 '21 at 06:10
  • Object.values? Is this what you mean? – vueAng Nov 18 '21 at 06:11
  • FYI you want `arr.push({ ...obj })` to break the object references – Phil Nov 18 '21 at 06:12
  • You're adding the *same object* to the array twice. If you modify that object, both references to that object will reflect those modifications. – Robby Cornelissen Nov 18 '21 at 06:12

1 Answers1

0

Objects are stored as references, so to push the object twice and change one of them, you want to push them by:

arr.push(JSON.parse(JSON.stringify(obj)));

If you push your object to your array in this way, you should be able to change one item and not have the other change.

OIRNOIR
  • 33
  • 6