admin管理员组文章数量:1415460
i have this array of Object :
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"
},
...
]
i want to an auto-incremntal id property for each object of my array , using forEach ( not looping with myArray.length )
Suggestions ?
i have this array of Object :
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"
},
...
]
i want to an auto-incremntal id property for each object of my array , using forEach ( not looping with myArray.length )
Suggestions ?
Share Improve this question asked Sep 13, 2018 at 16:46 firasKoubaafirasKoubaa 6,88530 gold badges87 silver badges164 bronze badges 3-
i want
sounds like you want us to do the work for you, instead of helping because you're stuck. What have you tried, what doesn't work? – VLAZ Commented Sep 13, 2018 at 16:48 -
so whats the problem? try
myArray = myArray.map((i, idx) => ({...i, id: idx}))
– givehug Commented Sep 13, 2018 at 16:50 - when iterate array.forEach((item,index)) , you will get item and index , the index you can use it as an id. – Jameel Moideen Commented Sep 13, 2018 at 16:50
2 Answers
Reset to default 4You can use forEach()
method as you want in your question:
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:
- the element value
- the element index
- 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);
This should do the trick
myArray.map(i => ({edoId: ++i.edoId ,storeName: i.storeName }))
本文标签: javascriptTypescriptAdd an autoincrement id attribute of each object in arrayStack Overflow
版权声明:本文标题:javascript - Typescript : Add an autoincrement id attribute of each object in array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745184535a2646621.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论