-1

I have the following array

["Design", "Survey", "Geotech", "Community", "Progress", "Planning", "Commercial", "Logistics", "Milestones", "Environment", "Quality", "Safety"]

and I would like to convert into it the following format, would be nice if the ids were random or unique

data = [
    {id: 1, title: 'Design'},
    {id: 2, title: 'Survey'},
    {id: 3, title: 'Geotech'},
    {id: 4, title: 'Community'},
  ];
} 
Almog
  • 2,639
  • 6
  • 30
  • 59

5 Answers5

5

You can access the index of the array element in the map callback function via the second parameter, so minimally it could be (if you don't care about whether id starts from 0 or 1):

var arr = ["Design", "Survey", "Geotech", "Community", "Progress", "Planning", "Commercial", "Logistics", "Milestones", "Environment", "Quality", "Safety"];

console.log(
  arr.map((title, id) => ({id, title}))
);

If starts from 1:

var arr = ["Design", "Survey", "Geotech", "Community", "Progress", "Planning", "Commercial", "Logistics", "Milestones", "Environment", "Quality", "Safety"];

console.log(
  arr.map((title, id) => ({id: id+1, title}))
);
Psidom
  • 209,562
  • 33
  • 339
  • 356
3

You can use map for that:

var array = ["Design", "Survey", "Geotech", "Community", "Progress", "Planning", "Commercial", "Logistics", "Milestones", "Environment", "Quality", "Safety"];

var id = 1;
var data = array.map(function(x) {
  return {
    id: id++,
    title: x
  };
});

console.log(data);
abagshaw
  • 6,162
  • 4
  • 38
  • 76
Hugo sama
  • 899
  • 1
  • 9
  • 19
1
   var oldarr = [
   "Design", "Survey", "Geotech", "Community", "Progress", 
   "Planning", "Commercial", "Logistics", "Milestones", "Environment", 
   "Quality", "Safety"];

   var newArr = oldArr.map(function (element,index) {
     return { id : index + 1, title:element};
   });
0

To generate Unique ID's, you can use this function from @broofa (taken from this answer) which uses window.crypto, then use it in the map method:

function uuidv4() {
    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => 
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    )
}

var data = ["Design", "Survey", "Geotech", "Community"];

var newArray = data.map(title => ({id: uuidv4(), title}));

console.log(newArray)

Note that the above uses a number of recent features, so not particularly compatible with older browsers.

RobG
  • 142,382
  • 31
  • 172
  • 209
DGaffneyDC
  • 152
  • 1
  • 2
  • 12
0

how about reduce

["Design", "Survey", "Geotech", "Community", "Progress", "Planning", "Commercial", "Logistics", "Milestones", "Environment", "Quality", "Safety"].reduce((accum , curr, indx) => accum.concat({id: indx+1, title: curr}), []);