简体   繁体   中英

How to transpose array of objects in TypeScript?

I am having an array of objects as below:

finalList = [
  [{name: john}, {name: max}, {name: rob}],
  [{id: 1}, {id: 2}, {id: 3}],
  [{gender: M}, {gender: F}, {gender: M}],
]

I need the array to transpose like this:

finalList = [ 
  {name: john, id: 1, gender: M},
  {name: john, id: 1, gender: M},
  {name: john, id: 1, gender: M}
]

The actual array of object is in nested array. Please help me guiding to transpose the array in TypeScript.

Here's a nice functional way. It assumes each array in finalList has the same length and same keys (so no error handling).

 const finalList = [ [{name: "john"}, {name: "max"}, {name: "rob"}], [{id: 1}, {id: 2}, {id: 3}], [{gender: "M"}, {gender: "F"}, {gender: "M"}], ]; console.log(finalList); // this is a trick to create an array of a specific size with unique objects inside it // the fill is necessary to iterate over the holed array (https://stackoverflow.com/q/40297442/2178159) // fill({}) won't work since it's a single object ref that will be shared const results = new Array(finalList.length).fill(null).map(() => ({})); finalList.forEach(group => { group.forEach((obj, i) => { Object.assign(results[i], obj); }) }); console.log(results);

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