使用JavaScript中的ID将数组转换为对象数组

Alm*_*ren -1 javascript arrays

我有以下数组

["Design", "Survey", "Geotech", "Community", "Progress", "Planning", "Commercial", "Logistics", "Milestones", "Environment", "Quality", "Safety"]
Run Code Online (Sandbox Code Playgroud)

我想将以下格式转换成它,如果id是随机的或唯一的,那就太好了

data = [
    {id: 1, title: 'Design'},
    {id: 2, title: 'Survey'},
    {id: 3, title: 'Geotech'},
    {id: 4, title: 'Community'},
  ];
} 
Run Code Online (Sandbox Code Playgroud)

Psi*_*dom 5

您可以map通过第二个参数访问回调函数中数组元素的索引,因此最低限度可能是(如果您不关心id是从0还是1开始):

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

console.log(
  arr.map((title, id) => ({id, title}))
);
Run Code Online (Sandbox Code Playgroud)


如果从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}))
);
Run Code Online (Sandbox Code Playgroud)