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

153
Views
Group items by common property in array of objects

I'm looking for an efficient way to rearrange an array of objects in JS. I need to combine two parameters from each object into a single object, where the gwdetailsid value is the same.

Initial array:

{
  "data": [
    {
      "gwdetailsid": "gw1",
      "gwpname": "username",
      "gwpvalue": "transalis"
    },
    {
      "gwdetailsid": "gw1",
      "gwpname": "password",
      "gwpvalue": "secure_password@1"
    },
    {
      "gwdetailsid": "gw2",
      "gwpname": "username",
      "gwpvalue": "tesco"
    },
    {
      "gwdetailsid": "gw2",
      "gwpname": "password",
      "gwpvalue": "lemon_farmer_2"
    }
  ]
}

The desired output array:

{
  "gateways": [
    {
      "gwdetailsid": "gw1",
      "username": "transalis",
      "password": "secure_password@1"
    },
    {
      "gwdetailsid": "gw2",
      "username": "tesco",
      "password": "lemon_farmer_2"
    }
  ]
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Effectively, your task comes down to transforming data array into gateways array.

You may employ Array.prototype.reduce() for that kind of job, to build up the Map with gwdetailsid property as a key, then extract .values() of that Map:

const data = [{gwdetailsid:"gw1",gwpname:"username",gwpvalue:"transalis"},{gwdetailsid:"gw1",gwpname:"password",gwpvalue:"secure_password@1"},{gwdetailsid:"gw2",gwpname:"username",gwpvalue:"tesco"},{gwdetailsid:"gw2",gwpname:"password",gwpvalue:"lemon_farmer_2"}],
      
      gateways = [...data
        .reduce((acc, {gwdetailsid, gwpname, gwpvalue} ) => {
          const group = acc.get(gwdetailsid)
          group
            ? group[gwpname] = gwpvalue
            : acc.set(gwdetailsid, {gwdetailsid, [gwpname]: gwpvalue})
          return acc
        }, new Map)
        .values()
      ]
      
console.log(gateways)
.as-console-wrapper{min-height:100%;}

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!