简体   繁体   English

Javascript Array to Object最佳方法

[英]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() . 使用Object.entries()提取键/值对(条目Object.entries() Iterate the entries with Array.map() . 使用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() : 通过传播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 . 假设您的对象名为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 . 假设每个值只有一个索引,另一种方法是使用函数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); 

I am not sure efficiency wise, but you can use the find function too! 我不确定效率是明智的,但是您也可以使用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