简体   繁体   中英

Map array into array of objects where for one element of array we may have multiple objects

Convert array of objects and array like [[{a:1,b:2},{c:3,d:4}],{e:5}] to single array of objects like [{a:1},{b:2},{c:3},{d:4},{e:5}] in javascript in optimal way. I used spread operator to flatten the array but {...[{a:1,b:2}] } gave {0:{a:1},1:{b:2}} which is adding extra key. Then I removed the key by iterating for all elements. Please help me with optimal solution.

Shortest

 var data = [[{a:1,b:2},{c:3,d:4}],{e:5}]; var result = [].concat(...data).reduce((ac,a) => ac.concat(Object.keys(a).map( k=>({[k]:a[k]}) )) ,[]); console.log(result); 

You can use array#reduce to flatten your array. Then, use array#reduce to get the individual key-value pair pair using array#map .

 var data = [[{a:1,b:2},{c:3,d:4}],{e:5}]; var getObject = (data) => { return data .reduce((r, b) => r.concat(b), []) .reduce((r,o) => r.concat(Object.keys(o).map(k => ({[k] : o[k]}))),[]); } console.log(getObject(data)); 

Flatten the arrays using Array#concat and spread , combine to a single object by spreading into Object#assign , get the entries , and map them to the requested form:

 const data = [[{a:1,b:2},{c:3,d:4}],{e:5}]; const result = Object.entries( Object.assign({}, ...[].concat(...data)) ).map(([k, v]) => ({ [k]: v })); console.log(result); 

You could check for an array and take a recursive approach for this case. If not map the entries for objects with a single property.

 var data = [[{ a: 1, b: 2 }, { c: 3, d: 4 }], { e: 5 }], result = data.reduce(function fn(r, a) { return r.concat(Array.isArray(a) ? a.reduce(fn, []) : Object.entries(a).map(([k, v]) => ({ [k]: v })) ); }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Something like this?

 console.log([[{a:1,b:2},{c:3,d:4}],{e:5}]. reduce((arr, element) => Array.isArray(element) ? [...arr, ...element] : [...arr, element], []). reduce((arr, element) => [...arr, ...Object.entries(element).map(([key, value]) => ({[key]: value}))], [])); 

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