繁体   English   中英

Javascript Array to Object最佳方法

[英]Javascript Array to Object best way

我有以下

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

我需要发送:

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

最快,最快的方法是什么?

使用Object.entries()提取键/值对(条目Object.entries() 使用Array.map()迭代条目。 对于每个条目,返回一个带有键的对象,以及一个没有包装数组的值。 通过传播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); 

假设您的对象名为obj 我会这样:

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); 

假设每个值只有一个索引,另一种方法是使用函数reduceObject.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); 

我不确定效率是明智的,但是您也可以使用find函数!

 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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM