0

I'm new in JavaScript programming then I got weird case like this. I have an one Array Object and one Array like below :

let data = [{"name": "Apple"} , {"name": "Orange"}, {"name": "Pineapple"}]
let selected = [];

I implement click in data when item clicked then the selected object in data move to selected. The data have no ID so I create the ID with its position index in selected. But if there is same object the position is same too. I try some code below but it does not work.

1.

  const dataObject = {"name": "Apple"};
  dataObject['position'] = selected.length;
  selected.push(dataObject);      
  const dataObject = {"name": "Apple"};
  selected.push(dataObject);
  for(let i = 0; i<selected.length; i++) {
    selected[i]['position'] = i;
  }

The weird case is if there is same object like Apple, Orange, Apple , I get the wrong ID in Array like :

[{"name": "Apple", position: 2} , {"name": "Orange", position: 1}, {"name": "Apple", position: 2}]

Edit

Here the reproducible code :

let data = [{"name": "Apple"} , {"name": "Orange"}, {"name": "Pineapple"}]
let selected = [];

const dataObject = {"name": "Apple"};
selected.push(dataObject);
selected.push(dataObject);
for(let i = 0; i<selected.length; i++) {
  selected[i]['position'] = i;
}

document.write('<br>' + JSON.stringify(selected));

// Output : [{"name":"Apple","position":1},{"name":"Apple","position":1}] 
// Output Expect: [{"name":"Apple","position":0},{"name":"Apple","position":1}] 

Where might be my mistake?

halfer
  • 19,824
  • 17
  • 99
  • 186
MrX
  • 953
  • 2
  • 16
  • 42
  • Please provide code to reproduce the issue, preferably without the click handler, but just sequentially executed code. Input, expected output, output you get. – trincot Oct 12 '20 at 06:11
  • you question is not very clear, if possible, try and update your question with - input data, code and its issue and expected output – kewlashu Oct 12 '20 at 06:18
  • I'm sorry, I edited and rebuild simple version in online editor. Sorry again – MrX Oct 12 '20 at 06:21

1 Answers1

0

dataObject is assigned by reference in selected array, so its the same object you are assigning twice, change in one will change both elements of selected array as they are same object.

See if below code helps

let data = [{"name": "Apple"} , {"name": "Orange"}, {"name": "Pineapple"}]
let selected = [];

const dataObject = {"name": "Apple"};

//assigning a new object to selected by using dataObject
selected.push({"name":dataObject.name});

//assigning a new object to selected by using dataObject
selected.push({"name":dataObject.name});

for(let i = 0; i<selected.length; i++) {
  selected[i]['position'] = i;
}

document.write('<br>' + JSON.stringify(selected));

Answers in this question can get you started to learn more

kewlashu
  • 1,099
  • 10
  • 18
  • I see, so Javascript pass the reference. Its new for me. Thank you for answer and the link – MrX Oct 12 '20 at 06:38