首页 > 解决方案 > How to make and object find its own index in an array?

问题描述

I have a simple array of objects with a id property and I need the ids to be equal to their index. I tried this

var arr = [

  {
    id: arr.indexOf(this),
    length: this.length
  },
   {
    id: arr.indexOf(this),
    length: this.length
  },
   {
    id: arr.indexOf(this),
    length: this.length
  }

]

But that doesn't work. Do I have to use a function outside the array to do this? None of the built in methods would help?

标签: javascriptarrays

解决方案


// If this.length =3
var arr = [
  {length: 3},
  {length: 3},
  {length: 3}
]

arr.forEach((item, index)=> item.id =index)
console.log(arr)


推荐阅读