Wednesday 16 February 2022

Convert Array of Object to array AND array to Array of Object - using map function in JS/TS

Convert  JSON ARRAY to Array

=========================

var someJsonArray  = [

                                   {id:1, name: 'name1', property:'value1'},

                                    {id:2, name: 'name2', property:'value2'},

                                    id:3, name: 'name3', property:'value3},

                                    ];


using Arrow function:

-------------------------

var arrayData = someJsonArray.map( item => item.property )     

/// output is ::: ['value1', value2','value3'];


///using without  Arrow (=>) function

-----------------------------------------------

var arrayData someJsonArray.map( function(item) { return item.property; } );  


Convert  ARRAY to JSON Array

=========================


var arr =  ['value1', value2','value3'];

let JsonArr = arr.map( val => { "key": val,"name": val, "value": val } 

 // this case all the key values same data   [{key:1, name: 'name1', val:'value1'}, {}, {}]

without Arrow Function( => )

let JsonArr = arr.map( function(val)=> { return {"name": val, "value": val }  }); 




No comments:

Post a Comment