【问题标题】:How to add an incremental index only to properties with the same value in JavaScript?如何仅将增量索引添加到 JavaScript 中具有相同值的属性?
【发布时间】:2022-06-13 20:20:50
【问题描述】:

我有这个数组:

myArray: [
 { name: "name1" }, { name: "name1" }, { name: "name1" },
 { name: "name2" }, { name: "name2" }, { name: "name2" },
]

而我的目标是:

myArray: [
 { name: "name1", index: 0 }, { name: "name1", index: 1 }, { name: "name1", index: 2 },
 { name: "name2", index: 0 }, { name: "name2", index: 1 }, { name: "name2", index: 2 },
]

【问题讨论】:

  • 你试图解决这个问题的代码 - 那在哪里?您应该将其作为minimal reproducible example 添加到您的问题中。
  • 您尝试了哪些方法,哪些没有按预期工作?
  • 为每个值添加一个计数器,遍历每个对象并更新适当的计数器?您可能可以使用 map 和值对象:索引对
  • 我已经尝试了一些解决方案,例如 map(),但我没有找到真正的解决方案。我没有很多其他的想法来做这件事
  • @jackcoral 请edit你的问题包括这个,以便我们可以帮助指出你做错了什么

标签: javascript arrays


猜你喜欢
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多