-1

I am trying to make an array with a unique Id, every time I push the id in the array is always the last index. This is the code I have tried:

locationData.forEach((data,index) => {
      if(1==data.id){
      data.uniqId= index
      myArray.push(data)                     
   }                 
});

What I get:

[{uniqId:3},[{uniqId:3},[{uniqId:3}]

What I want

[{uniqId:1},[{uniqId:2},[{uniqId:3}] 
  • the `push()` method inserts the new element at the end of the array. [Are you trying to add a new item to the start of the array?](https://stackoverflow.com/questions/8073673/how-can-i-add-new-array-elements-at-the-beginning-of-an-array-in-javascript) – terahertz May 14 '20 at 10:48
  • No, what I want is that the first element gets the id of 1 the second index gets the id of 2 etc... the result I get now is all the elements have the last index as the id. What I get:[{uniqId:3},[{uniqId:3},[{uniqId:3}] What I want: [{uniqId:1},[{uniqId:2},[{uniqId:3}] – Joseph Castillo May 14 '20 at 11:11
  • @JosephCastillo What's that `if` condition doing there? Can you simply do this? `locationData.forEach((data,index) => { myArray.push({uniqueId: index+1}); });` – ABGR May 14 '20 at 12:47
  • 1
    I'm not sure "what you're getting" is correct since your output mentions only "uniqueId" whereas your `data`, from the code you've written, seems to contain a field `id` as well. – ABGR May 14 '20 at 12:51

2 Answers2

1

Your code works for me if locationData is an array containing objects with the property "id".

var locationData = [{id: 1},{id:1}];
var myArray = [];
locationData.forEach((data,index) => {
      if(1==data.id){
      data.uniqId= index + 1
      myArray.push(data)                     
   }                 
});
console.log(myArray)

If your locationData has some nested things, you may have to flatten the array:

var locationData = [[{id: 1},{id:1}], {id:2}];
locationData = locationData.flat(1);
Sev
  • 533
  • 3
  • 7
0

The problem I was having is that instead of creating a Deep copy I was just creating a variable, I did this to fix it:

locationData =JSON.parse(JSON.stringify(locationData))

and after that run through the array. It worked.