0

As a newbie, I'm looking for the best approach to achieve the below:

Here is the Array I get from my DB query that contains a left join on the "class" table

[
{"legnumber":1,
"classcode" : "J"},
{"legnumber":1,
"classcode" : "Y"},
{"legnumber":2,
"classcode" : "J"}
]

And I would like to get something like this:


    {
            "legs": [
                    {
                    "legnumber" : 1,
                    "classes" : [
                                    {"classcode" : "J"},
                                    {"classcode" : "Y"}
                                    ] 
                    },
                    {
                    "legnumber" : 2,
                    "classes" : [
                                    {"classcode" : "J"}
                                    ]
                    }
                    ]
    }

Thanks a lot for your suggestions. I'm using Sequelize in this project but I'm writing raw queries as I find it more convenient for my DB model.

Regards, Nico

0

2 Answers 2

0

Hassan's answer is the more concise way to handle this, but here is a more verbose option to help understand what's happening:

const queryResults = [
  { legnumber: 1, classcode: 'J' },
  { legnumber: 1, classcode: 'Y' },
  { legnumber: 2, classcode: 'J' },
]

// create an object to store the transformed results
const transformedResults = {
  legs: [],
}

// loop through each item in the queryResult array
for (const result of queryResults) {

  // try to find an existing leg tha matches the current leg number
  let leg = transformedResults.legs.find((leg) => leg.legnumber === result.legnumber)

  // if it doesn't exist then create it and add it to the transformed results
  if (!leg) {
    leg = {
      legnumber: result.legnumber,
      classes: [],
    }
    transformedResults.legs.push(leg)
  }

  // push the classcode
  leg.classes.push({ classcode: result.classcode })
}

console.log(transformedResults)

Sign up to request clarification or add additional context in comments.

Comments

0

You can group your array items based on legnumber using array#reduce and then get all the values to create your result using Object.values().

const arr = [ {"legnumber":1, "classcode" : "J"}, {"legnumber":1, "classcode" : "Y"}, {"legnumber":2, "classcode" : "J"} ],
      output = arr.reduce((r, {legnumber, classcode}) => {
        r[legnumber] ??= {legnumber, classes: []};
        r[legnumber].classes.push({classcode});
        return r;
      },{}),
       result = {legs: Object.values(output)};
console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.