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

时间:2017-08-08 00:08:30

标签: javascript arrays

我有以下数组

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

我希望将以下格式转换为它,如果id是随机的或唯一的,那将会很好

data = [
    {id: 1, title: 'Design'},
    {id: 2, title: 'Survey'},
    {id: 3, title: 'Geotech'},
    {id: 4, title: 'Community'},
  ];
} 

5 个答案:

答案 0 :(得分: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}))
);




如果从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}))
);




答案 1 :(得分:3)

您可以使用map



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);




答案 2 :(得分: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};
   });

答案 3 :(得分:0)

要生成唯一ID,您可以使用@broofa(taken from this answer)中使用window.crypto的此功能,然后在地图方法中使用它:



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)




请注意,上面使用了许多最新功能,因此与旧版浏览器并不特别兼容。

答案 4 :(得分:0)

如何减少   

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