简体   繁体   中英

Javascript Array to Object best way

I have the following

 {
 bill: [ 
        { satisfy: 'true', comments: '' } 
       ],
 permission_title: [ 
        { satisfy: 'false', comments: '5' } 
       ],
 final_status: [ 
       { satisfy: 'true', comments: '' } 
       ] 
 }

And i need to send:

{
 bill: { satisfy: 'true', comments: '' },
 permission_title: { satisfy: 'false', comments: '5' },
 final_status: { satisfy: 'true', comments: '' } 
 }

What is the best and fast way to get it?

Extract the key/value pairs (entries) with Object.entries() . Iterate the entries with Array.map() . For each entry return an object with the key, and the value without the wrapping array. Merge back to an object by spreading into Object.assign() :

 const obj = {"bill":[{"satisfy":"true","comments":""}],"permission_title":[{"satisfy":"false","comments":"5"}],"final_status":[{"satisfy":"true","comments":""}]}; const result = Object.assign( ...Object.entries(obj).map(([k, v]) => ({ [k]: v[0] })) ); console.log(result); 

Let's say your object is named obj . I would do it this way:

for(var p in obj) obj[p] = obj[p][0];

 const obj={ bill: [ { satisfy: 'true', comments: '' } ], permission_title: [ { satisfy: 'false', comments: '5' } ], final_status: [ { satisfy: 'true', comments: '' } ] } let obj_new=Object.assign(obj); for(var p in obj_new) { obj_new[p] = obj_new[p][0] }; console.log(obj_new); 

Assuming that every value has only one index, an alternative is using the function reduce along with the function Object.keys .

 var obj = { bill: [{ satisfy: 'true', comments: '' }], permission_title: [{ satisfy: 'false', comments: '5' }], final_status: [{ satisfy: 'true', comments: '' }]}, result = Object.keys(obj).reduce((a, k) => (Object.assign(a, {[k]: obj[k][0]})), {}); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

 const src = { bill: [ { satisfy: 'true', comments: '' } ], permission_title: [ { satisfy: 'false', comments: '5' } ], final_status: [ { satisfy: 'true', comments: '' } ] }; const dest = Object.keys(src).reduce((prev, key) => { prev[key] = src[key][0]; return prev; }, {}); console.log(dest); 

I am not sure efficiency wise, but you can use the find function too!

 const src = { bill: [ { satisfy: 'true', comments: '' } ], permission_title: [ { satisfy: 'false', comments: '5' } ], final_status: [ { satisfy: 'true', comments: '' } ] }; const dest = Object.keys(src).reduce((prev, key) => { if(Array.isArray(src[key])) { prev[key] = src[key].find(() => true); } return prev; }, {}); console.log(dest); 

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