Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
How to project a key into an array to produce an array of objects?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!