Warm tip: This article is reproduced from stackoverflow.com, please click
javascript

How to traverse the attribute name plus [i] to count?

发布于 2020-03-27 10:17:15

For example, the object property name has a number, I want to add a property to the for traversal object, the property name must have a number.

The printed results are as follows:

[{
    room[1]: 1
  },
  {
    room[2]: 2
  },
  {
    room[3]: 3
  },
  {
    room[4]: 4
  },
  {
    room[5]: 5
  },
  {
    room[6]: 6
  }
]

var = arr[]
for (let index = 0; index < 10; index++) {
  arr.push({
    `room[${index}]`: index,
  })
}
console.log(arr)
Questioner
wen tian
Viewed
17
Ele 2019-07-03 21:27

Is missing something called computed-property names:

Assuming there is a typo in the declaration of the variable arr

var arr = [];
for (let index = 0; index < 10; index++) {
  arr.push({
    [`room[${index}]`]/*Computed-property names*/: index,
  });
}
console.log(arr)
.as-console-wrapper { min-height: 100%; }