简体   繁体   中英

What is the best way to convert an array of strings into an array of objects in Angular 2?

Let's say I have an array as follows:

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

I need to convert it into an array of objects that looks like this:

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

You can use map to iterate over the original array and create new objects.

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

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

You can check a working example here .

The solution of above problem is the map() method of JavaScript or Type Script.

map() method creates a new array with the results of calling a provided function on every element in the calling array.

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

Please follow following links:

TypeScript

JS-Fiddle

We can achieve the solution of above problem by for loop :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM