如何反复更改数组对象中的值累加器

时间:2019-04-05 12:46:21

标签: javascript

输入:-   在这里,我有重复natraj的数组对象,因此我需要像给定示例一样附加一些计数。

var aa= [
     {name:'natraj'},
     {name:'ajai'},
     {name:'natraj'},
     {name:'ajai'},
     {name:'barath'},
     {name:'ajai'},
     {name:'barath'},
     {name:'natraj'},
   ]

输出:-

  [
     {name:'natraj'},
     {name:'ajai'},
     {name:'natraj_1'},
     {name:'ajai_1'},
     {name:'barath'},
     {name:'ajai_2'},
     {name:'barath_1'},
     {name:'natraj_2'},
   ]

1 个答案:

答案 0 :(得分:5)

保持连续计数:

var aa = [{name:'natraj'},{name:'ajai'},{name:'natraj'},{name:'ajai'},{name:'barath'},{name:'ajai'},{name:'barath'},{name:'natraj'},]

let counts = {}
aa.forEach(o => {
  if (counts[o.name]) {
    o.name += `_${counts[o.name]++}`
  } else {
    counts[o.name] = 1
  }
});

console.log(aa)