-2

Error trying to assignment objects in javascript

Image of output

let info = {
  ID: '',
}

let ids = ["0", "1", "2", "3", "4"]

ids.forEach((i) => {
  info.ID = i
  console.log(info)
});

I expect the output of this code to be an object info with ID 1 to 4, but the actual output is info.ID = 4

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
nestor-gm
  • 3
  • 1
  • Read this: https://stackoverflow.com/a/48969647/4350275 – Prerak Sola Oct 16 '19 at 08:48
  • You're updating the property ID to equal whatever i is in the loop. Since "4" is last in the loop, info.id will equal "4". – henrik123 Oct 16 '19 at 08:48
  • `info.id = ids`, otherwise you are just rewriting I'd property each loop iteration. – freeek Oct 16 '19 at 08:49
  • It's unclear what result you expect. *"an object info with ID 1 to 4"* how can one object have one property with 4 different values at the same time? – Thomas Oct 16 '19 at 08:56

6 Answers6

1

You do not need the object. Simply use map on the array:

let ids = ["0", "1", "2", "3", "4"]

let info = ids.map(i => ({ID: i}));

console.log(info);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Of course, you are iterating over an array and assign the ID with the value of each item in the array.

If you want to assign the property ID with the array just use this:

let info = {
 ID : ["0", "1", "2", "3", "4"]
} 

console.log(info);

It's unclear what you are trying to achieve with the forEach loop.

Verthosa
  • 1,671
  • 1
  • 15
  • 37
0

let ids = ["0", "1", "2", "3", "4"]
let info = {
    ID: ids
}
console.log(info);

Note: You just need to assign your local variable name to the object element.

Parth Raval
  • 4,097
  • 3
  • 23
  • 36
0

You can try this:

let info = []

let ids = ["0", "1", "2", "3", "4"]

ids.forEach((i) => {
  info.push({ID : i})
  console.log(info)
});
Dino
  • 7,779
  • 12
  • 46
  • 85
raq
  • 57
  • 1
  • 3
0

You may need an array of info object.

let infos = []

let ids = ["0", "1", "2", "3", "4"]

ids.forEach((i) => {
  let info = {ID: i};
  infos.push(info);
});

infos.forEach((info) => console.log(info.ID));
Max Peng
  • 2,879
  • 1
  • 26
  • 43
0

You are just re-writing the ID over and over again. You should push new value of id always.

function solve() {
      let info = [];

      let ids = ['0', '1', '2', '3', '4'];

      for (const id of ids) {
        info.push({ ID: id });
      }

      console.log(info);
    }

    solve();