Home > Software design >  How to project a key into an array to produce an array of objects?
How to project a key into an array to produce an array of objects?

Time:10-31

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.

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can easily achieve the result with reduce and map

const src = {
  a: [1, 2, 3],
};
const result = Object.keys(src).reduce(
  (acc, curr) => [...acc, ...src[curr].map((val) => ({ [curr]: val }))],
  []
);
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related