ecmascript 6 - Reduce javascript object -


i have javascript object :

{     {         long_name: "10",         types: [             0: "street_number"         ],     },     {         long_name: "street",         types: [             0: "route"         ],     },     {         long_name: "paris",         types: [             0: "locality"         ],     },     ... } 

and want flatten , have :

{     street_number: "10",     route: "street",     locality: "paris",     ... } 

i using es6, can't manage flatten much, i've succeeded having :

{     {street_number: "10"},     {route: "street"},     {locality: "paris"},     ... } 

here tried :

const flattenedobject = originalobject.map(flatten); ... function flatten(element) {     let obj = {};     obj[element.types[0]] = element.long_name;      return obj; } 

thanks help.

you use array#reduce computed property , first element array.

the key feature object.assign adding properties result object.

the object.assign() method used copy values of enumerable own properties 1 or more source objects target object. return target object.

var data = [{ long_name: "10", types: ["street_number"], }, { long_name: "street", types: ["route"], }, { long_name: "paris", types: ["locality"], }],      object = data.reduce((r, a) => object.assign(r, { [a.types[0]]: a.long_name }), {});    console.log(object);


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -