Home > Blockchain >  convert array of json label in javascript
convert array of json label in javascript

Time:08-16

I have array of JSON like

 [
{title:'button'},
{title:'button'},
{title:'button'},
{title:'button'},
] 

and want to convert it as

[
{title:'button 1'},
{title:'button 2'},
{title:'button 3'},
{title:'button 4'},
]

CodePudding user response:

Try this please

    var arrJson = [
{title:'button'},
{title:'button'},
{title:'button'},
{title:'button'},
] ,

arrJson.forEach((e,i)=>{
    arrJson [i]['title'] = arrJson[i]['title']   " "   i;
})

CodePudding user response:

Use a simple map to mutate each object in the array by adding the index:

[{ title: 'button' }, { title: 'button' }, { title: 'button' }, { title: 'button' }].map(
  (obj, idx) => {
    obj.title = `${obj.title} ${idx   1}`;
    return obj;
  },
);

CodePudding user response:

Just use .map:

arr.map(({ title }, i) => ({ title: `${title} ${i   1}`}));
  • Related