Tips on converting Sequelize response to an array of strings instead of objects

When utilizing Sequelize on a join query, I am currently facing the issue where the data from the join table is presented as an array of objects instead of strings. The client specifically needs an array of strings.

Is it possible and advisable to achieve this with Sequelize? Or should I manually transform the data before sending it to the client?

Query

movie.findOne({
        include: [
          {
            model: db.genre,
            attributes: ['name'],
            through: {
              attributes: [],
            },
          },
      })

Output

{
  "id": 52,
  "type": "movie",
  "Genres": [
      {
          "name": "Action"
      },
      {
          "name": "Comedy"
      }
  ]
}

My ideal format for Genres would be:

"Genres": ["Action", "Comedy"]

Answer №1

Although not achievable directly with pure sequelize, it can be easily accomplished by formatting the object post-query.

ob.Genres = ob.Genres.map(x=>x.name);
 // { id: 52, type: 'movie', Genres: [ 'Action', 'Comedy' ] }

Alternatively, you could utilize a sequelize literal to group the desired data as a separate attribute, but this approach is needlessly complex.

movie.findOne({
    where:{
        id:52
    },
    attributes: [
            'id','type',
            [Sequelize.literal(`
                (
                SELECT GROUP_CONCAT(name)
                    FROM Genres
                    WHERE
                        movieId = 52
                )`), 'Genres'],
            ] 
})

Assuming certain aspects of your database structure, this method allows for grouping all names from a query result and storing them in a new attribute.

It is recommended to manually map the value after querying instead.

Answer №2

Utilize Sequelize's pluck method to easily extract specific properties from an array of objects. This method allows you to specify the property you wish to extract and returns an array containing those values.

const result = movie.findByPk({
    include: [
      {
        model: db.genre,
        attributes: ['name'],
        through: {
          attributes: [],
        },
      },
  });

  const extractedValues = result.map(obj => obj.property);
  console.log(extractedValues);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to set up CORS in IE11 using C# with JQuery.ajax?

Having some trouble with CORS functionality in IE11. I need to perform ajax requests using jquery (or whatever the browser supports natively), without any additional libraries. These requests are cross-domain and function perfectly in Chrome and Firefox. ...

Firefox 44 experiencing issue with HTML 5 Video playing sounds unexpectedly

There has been an unusual observation of Firefox playing the sounds of all embedded videos on a page, even when the elements themselves are not actively playing. Clicking play on the video controls triggers new sound and video playback to start. All video ...

verifying the presence of offspring in knockout js

Utilizing knockout for displaying items on the page, I have a series of groups such as Group 1, Group 2, etc. Each group is contained within its own div. Upon clicking on a group, it expands to showcase the items within that specific group. However, some o ...

Rollup does not allow the use of self-written component imports in a component library

I am in the process of creating a personalized component library using my own components. However, I am encountering difficulties in the final stage of constructing the library using rollup. The current structure of my folders is as follows: ├── src ...

Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png Despite my attempts, nothing seems to work. Here is the method ...

unable to update database using jquery ajax

Hello everyone, this is my first time posting on Stackoverflow! I am facing an issue while trying to run an "Insert" query using Jquery's $.ajax function. Upon checking the network tab on Chrome Dev Tools, it seems like my file is being loaded but th ...

Is there a way to verify the existence of an email address, generate an error if it does, and create a user only if there is no match

I have been having trouble with a specific function in my code. I am trying to validate if the email entered by the user already exists in the database. If it does, I want to throw an error, and if it doesn't, then I proceed to creating the new user. ...

Calculating grand total upon form initialization

Hey there! I'm working on an input that fetches values and triggers the fntotal function to show a total. The issue I'm facing is that when the form loads, the total doesn't display initially - it only works when values are changed. <inp ...

Display upon hovering, conceal with a button located within a popup container

There seems to be an issue with the code below. Even though it works perfectly in jsfiddle, it breaks in my Chrome and other browsers right after displaying the ".popup" div. Can anyone point out what I might be doing wrong? I found similar code on this si ...

Encountering the error message "Type '{ theme: Theme; }' is not compatible with type" while attempting to pass it as a prop to the App component

Trying out a new strategy for my app initialization by incorporating the use of the useLocation hook within my App component. I'm still learning Typescript and encountering a problem. This is what I have so far: // index.tsx const theme: Theme = cre ...

Retrieve the HTML code from a file and store it in a JavaScript variable

My PhoneGap application is able to load an external page in the inAppBrowser and inject a bottom bar onto that page using executeScript(). This allows me to have a bar with basic controls on the specific page. I have successfully implemented this functiona ...

Implementing Decimal Input in Bootstrap-Vue for Google Chrome on Android

Issue is isolated to Google Chrome for Android (version 90.0.4430.210) and not present in other browsers. We have an input field that only allows numeric characters, structured like this: https://i.sstatic.net/zi4qn.png <b-form-input v-model="m ...

Troubleshooting Problem with NodeJS Https.request

Attempting to create a test post for the Zip API: Zip Api Here is the JSON data posted, following Zip Pay's example - { "shopper": { "title": "Mr", "first_name": "John", "last_name ...

Streamline user access with automatic JWT authentication in Vue application

When it comes to authorizing actions and accessing protected resources from my backend, I rely on jwt tokens for security. Here is an overview of the technologies used in both the frontend and backend: Frontend: Vue, Vue Router, VueX, Vuetify Backend: Ex ...

Is it possible for Express JS to receive incoming requests from external sources and then transmit the retrieved data to the front end of

I am currently developing a React JS frontend for my application, but I have an interesting idea to incorporate an external mobile app that can control certain elements on the screen, such as font styles. To achieve this functionality, I require the web ap ...

Retrieve props in a Vue component using the available context

As a newcomer to the VUE world, I have begun creating an app to display a list of TODO's. Passing the todo items through props to the todo component felt like the right approach, but I found myself searching for a more efficient way to share props wit ...

Changing the string "2012-04-10T15:57:51.013" into a Date object using JavaScript

Is there a way to transform the format "2012-04-10T15:57:51.013" into a Date javascript object using either Jquery or plain Javascript? ...

Tips for running multiple JavaScript functions in ASP.NET using Button's OnClientClick property

Is there a way to execute multiple JavaScript functions in ASP.NET to perform various tasks such as inserting a desired text in a TextBox, changing the TextBox background color and font color, and disabling or locking a Button for a specific duration? I ha ...

After switching from jQuery to pure JavaScript, the code is now up and

After initially coding in jQuery + AJAX, I attempted to rewrite it in vanilla JavaScript. However, the code is not functioning as expected now. Can someone help me identify the mistake causing nothing to display when I run it through the server? I have che ...

Error message "Uncaught TypeError: Unable to read property 'defaultView' of undefined" was encountered while using Google Maps

I am encountering an issue when attempting to load a Google map in React: "Uncaught TypeError: Cannot read property 'defaultView' of undefined" The problem seems to be isolated within this particular component, as the rest of the app renders su ...