【问题标题】:Adding an incrementing number to each object in an array of objects with Javascript [closed]使用Javascript为对象数组中的每个对象添加递增数字[关闭]
【发布时间】:2021-11-16 03:26:27
【问题描述】:

假设我有一个对象数组:

const myArray = [{ color: 'red' }, { color: 'blue'}, { color: 'yellow'}]

如何扩展对象以将键值对添加到键为 number 且值是每个对象中递增 1 的每个元素?我想要的结果是:

const myNewArray = [{ color: 'red', number: 1 }, { color: 'blue', number: 2 }, { color: 'yellow', number: 3 }]

【问题讨论】:

  • 这应该是一个简单的for 循环。您也可以使用.map()。数字是数组索引 + 1。
  • 为什么不简单地从数组中给定对象的索引推断number

标签: javascript arrays object increment


【解决方案1】:
const myNewArray = myArray.map((item, index) =>  { return {"number" :index, ...item} } )

【讨论】:

  • 也许您应该将答案更新为:const myNewArray = myArray.map((item, index) => { return {"number" :index + 1, ...item} } ),因为它需要 1..3,而不是 0..2。总体而言,您的答案解决了原始请求。 @brendanreape88 应该考虑将此标记为已解决。
猜你喜欢
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 2020-11-05
  • 2015-06-01
  • 2023-03-10
  • 2021-11-01
  • 2019-07-29
  • 1970-01-01
相关资源
最近更新 更多