簡體   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