在Angular 2中将字符串数组转换为对象数组的最佳方法是什么?

时间:2017-05-30 10:14:12

标签: javascript typescript

假设我有一个数组如下:

types = ['Old', 'New', 'Template'];

我需要将它转换为如下所示的对象数组:

[
    {
        id: 1,
        name: 'Old'
    },
    {
        id: 2,
        name: 'New'
    },
    {
        id: 3,
        name: 'Template'
    }
]

2 个答案:

答案 0 :(得分:0)

您可以使用 map 迭代原始数组并创建新对象。

let types = ['Old', 'New', 'Template'];

let objects = types.map((value, index) => {
  return {
    id: index + 1,
    name: value
  };
})

您可以查看一个有效的示例here

答案 1 :(得分:0)

上述问题的解决方案是JavaScript或Type Script的map()方法。

  

map()方法创建一个包含调用结果的新数组   在调用数组中的每个元素上提供的函数。

let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
/*map() method creates a new array with the results of calling 
a provided function on every element in the calling array.*/

     let types = [
         'Old',
         'New',
         'Template'
        ];


  /*
    let newArray = arr.map((currentvalue,index,array)=>{
         return Element of array
     });
  */


   let Obj = types.map((value, i) => {
         let data = {
                 id: i + 1,
                 name: value
             };

      return data;
    });

    console.log("Obj", Obj);

请点击以下链接:

TypeScript

JS-Fiddle

  

我们可以通过for循环实现上述问题的解决方案:

let types = [
    "One",
    "Two",
    "Three"
];

let arr = [];

for (let i = 0; i < types.length; i++){
    let data = {
        id: i + 1,
        name: types[i]
    };
    arr.push(data);
}

console.log("data", arr);
相关问题