gpt4 book ai didi

javascript - typescript : Add an autoincrement id attribute of each object in array

转载 作者:行者123 更新时间:2023-11-30 14:23:33 26 4
gpt4 key购买 nike

我有这个对象数组:

myArray = [
{
"edoId": "4010",
"storeName": "ABBEVILLE"
},
{
"edoId": "3650",
"storeName": "AGEN"
},
{
"edoId": "3298",
"storeName": "AIX ALLEES PROVENCALES"
},
{
"edoId": "3309",
"storeName": "AIX JAS DE BOUFFAN"
},
{
"edoId": "3313",
"storeName": "AIX LA PIOLINE"
},
{
"edoId": "2119",
"storeName": "AIX LES BAINS"
},
...
]

我想为数组的每个对象设置一个自动递增的 id 属性,使用 forEach(不使用 myArray.length 循环)

建议?

最佳答案

您可以使用 forEach()您在问题中想要的方法:

myArray.forEach(function(item, index){
item.id = index;
// or do whatever you want using index
});

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays). callback is invoked with three arguments:

  1. the element value
  2. the element index
  3. the array being traversed

var myArray = [
{
"edoId": "4010",
"storeName": "ABBEVILLE"
},
{
"edoId": "3650",
"storeName": "AGEN"
},
{
"edoId": "3298",
"storeName": "AIX ALLEES PROVENCALES"
},
{
"edoId": "3309",
"storeName": "AIX JAS DE BOUFFAN"
},
{
"edoId": "3313",
"storeName": "AIX LA PIOLINE"
},
{
"edoId": "2119",
"storeName": "AIX LES BAINS"
}
];

myArray.forEach(function(item, index){
item.id = index;
});

console.log(myArray);

关于javascript - typescript : Add an autoincrement id attribute of each object in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52318280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com