el_pup_le
el_pup_le

Reputation: 12189

How to map array to object with Typescript

How can I convert this array:

['black', 'grey', 'dark grey'];

To this:

[ MyObject { name: 'black', description: 'colour is black' }, MyObject { ... } ]

Upvotes: 1

Views: 260

Answers (3)

Arun Panneerselvam
Arun Panneerselvam

Reputation: 2333

Another straight forward method using a global type declare (global declaration helps you use it anywhere in the entire project),

declare global { // you can still define type without declaring it globally
  type Dictionary<T> = { [key: string]: T };
  type DefaultResponse = { 
    success: boolean,
    message: string,
  }
}

interface MyObject { 
    name: string,
    description: string 
  }

and in your function,

  var items = ['black', 'grey', 'dark grey']
  var results:[Dictionary<MyObject> | []]  = []

  items.reduce((result, field, index) => { 
    var _obj:Dictionary<string| any> =  { name: field , description : `The colour is ${field}` }
    results.push(_obj)
    return result;
  }, {})

  console.log(results)

view it in playground action: PlayGround

PS: If you'll use this frequently for more array with different keys, here's the more generalized solution:

 const destructureArray = (expectedKeys:any) => { 
    var aligned:[Dictionary<MyObject> | []]  = []
    var description = "The colour is "
    expectedKeys.reduce((param:any, field:any, index:any) => { 
        var _obj:Dictionary<string| any> =  {  name: field, description: `${description}: ${field}` }
        param = Object.assign(param, _obj)
        aligned.push(_obj)
       return param;
    }, {})
    return aligned;
   }

and the function call,

var expected = ['black', 'grey', 'dark grey']
var parsed = destructureArray( expected)
console.log(parsed)

Upvotes: 0

jburtondev
jburtondev

Reputation: 3263

Simple version

['black', 'grey', 'dark grey'].map((color) => { return {name: color, description: `colour is ${color}`}});

Best/Better practice

interface Color {
  name: string;
  description: string;
}

type Colors = Color[];

const colors: string[] = ['black', 'grey', 'dark grey'];

colors.map((colour): Colors => ({ name: colour, description: `colour is ${colour}` }));

Upvotes: 3

pzaenger
pzaenger

Reputation: 11992

A first straight forward solution: define an interface Colour, create a new array, here: colours, and iterate through your old array to push items into your new one:

interface Colour {
  name: string;
  description: string;
};

const colours: Colour[] = [];

['black', 'grey', 'dark grey'].forEach((colour: string) => {
  colours.push({
    name: colour,
    description: `colour is ${colour}`
  });
});

Using map instead:

const colours: Colour[] = ['black', 'grey', 'dark grey'].map(colour => {
  return {
    name: colour,
    description: `colour is ${colour}`
  };
});

Upvotes: 4

Related Questions