Given this source object:
const src = { a: [1, 2, 3]} }
I want to transform it to an array of objects representing all combinations(3):
[{a: 1}, {a: 2}, {a: 3}]
The code I currently have works, but feels inelegant:
const arrPairs = [];
Object.keys(src).map((el) => {
src[el].forEach(element => {
arrPairs.push({[el]: element});
});
});
I have a feeling that some combination of map/reduce would do this far cleaner I just can't figure it out.
You can iterate over the entries with .flatMap and map each value to its associated object.
const src = { a: [1, 2, 3],
b: [4, 5, 6, 7],
c: [8, 9, 10, 11, 12] };
const result = Object.entries(src)
.flatMap(([key, arr]) => arr.map(val => ({[key]: val})));
console.log(result);