Es6 way to convert object key value to one single object

  • A+
Category:Languages

I want to convert all data into one object,

let d = {   "Coupon_Code": "code",   "Coupon_Name": "namie",   "Coupon_Desc": 1000,   "selectedCity": [     {       "Coupon_City_Name": "xyz"     }   ],   "selectedCategory": [     {       "Coupon_Category_Name": "Shopping"     }   ],   "selectedCompany": [     {       "Coupon_Company_Name": "Shopper Stop"     }   ],   "selectedState": [     {       "Coupon_State_Name": "abc"     }   ],   "Coupon_Date": "2222-02-22", } 

i tried some methods of Object like keys , entries but dont no what to use. Final output should be

let d = {   Coupon_Code: "code",   Coupon_Name: "namie",   Coupon_Desc: 1000,   Coupon_City_Name: "xyz",   Coupon_Category_Name: "Shopping",   Coupon_Company_Name: "Shopper Stop",   Coupon_State_Name: "abc",   Coupon_Date: "2222-02-22", }; 

what's the best and optimum way to have above result using Venila Js and Es6

 


Reduce the entries of the original object. If the entry's value is an array merge the 1st element, if not merge the original key and value. You can merge the properties into the object using object spread:

const data = {"Coupon_Code":"code","Coupon_Name":"namie","Coupon_Desc":1000,"selectedCity":[{"Coupon_City_Name":"xyz"}],"selectedCategory":[{"Coupon_Category_Name":"Shopping"}],"selectedCompany":[{"Coupon_Company_Name":"Shopper Stop"}],"selectedState":[{"Coupon_State_Name":"abc"}],"Coupon_Date":"2222-02-22"};  const result = Object.entries(data)   .reduce((r, [k, v]) => ({     ...r,     ...Array.isArray(v) ? v[0] : { [k]: v }   }), {});  console.log(result);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: