Breaking down object properties to 'this' using destructuring in javascript

I would like to set the pagination result from response.data to Vue data.
The standard approach would be:

    this.resultData = response.data.results
    this.totalResults = response.data.total
    this.perPageResults = response.data.per_page

However, I am curious if there is a more efficient ES6 method to directly assign the result to something like this:

    const page = { results: data, total: total, per_page : perPage } = response.data
    this = { ...this, ...page }

Please note that the code snippet above does not function correctly.

Answer №1

Not possible to reassign this.

If only the data object has properties and you want to change the per_page property of response.data to perPage, then using Object.assign is an option:

Object.assign(this, response.data);

If there are other properties in the data object or renaming per_page is not allowed, try this approach:

const { data, total, per_page : perPage } = response.data
Object.assign(this, { data, total, perPage });

Answer №2

After studying @CertainPerformance's response and delving into the topic of fetching specific properties of an object from How to extract a subset of properties from a JavaScript object

I managed to come up with a functional solution using object destructuring.

    const page = (({ data, total, per_page: perPage }) => ({ data, total, perPage }))(response.data)
    Object.assign(this, page)

However, I found that this code did not make it any shorter or easier to understand, so I reverted back to the more traditional approach.

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

Tips for ensuring a div stays centered while resizing the window

When I resize the window, the div tab on the right side of the screen moves to the bottom right. How can I make it stay in the middle regardless of screen size? I've tried using margin-left:auto and margin-right:auto but it didn't work. Changing ...

Out of nowhere, while trying to update the app's packages with npm install, I encounter the following unexpected error

Error in module exports due to unexpected identifier. SyntaxError: Unexpected identifier > at Object.exports.runInThisContext (vm.js:76:16) > at Module.\_compile (module.js:542:28) > at Object.Module.\_extensions..js (module.js: ...

Pass the PHP data back to my existing webpage for JavaScript to retrieve

I recently set up a form on my WordPress website for users to submit data. Once the form is submitted, I use AJAX to create a new post without having to reload the page. I now need to figure out how to pass the post ID, a simple integer, back to the page s ...

A guide on parsing a nested JSON file with ExtJS 4

Here is the content of my JSON file named "jobInfo.json": { "job": { "id": 1, "name": "Job 1", "description": "bla bla bla", "locations": { "type": "FeatureCollection", "features": [{ "id": 1, "t ...

Ways to access a field value in SAPUI5

As I delve into OPENUI5/SAPUI5, I'm faced with the task of accessing data for the controls I've implemented. For instance: <Label text="Amount" /> <Input id="inputAmount" value="{Amount}" /> <Text id="lblCurrency" text="USD" > ...

Error: The function isInitial of chunk cannot be found

Currently, I am attempting to build my program using the following command: "build": "NODE_ENV='production' webpack -p", However, I encountered an error message: node_modules/extract-text-webpack-plugin/index.js:267 var shouldE ...

What is the best method for showcasing a nested JSON value?

I need to show the data for the month of April. Here is the code snippet: {{my_dates['2018-04-23']}} This code displays: { "april":0, "may":0, "june":0, "july":0, "august":0, "september":0, "october":0, "income_trips":" ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

An error was encountered in customizing CKEditor5 in Vue: compilation unsuccessful

I tried to integrate a custom CKEditor5 into my Vue application, but encountered a failed to compile error. I generated the custom build using the online tool provided by CKEditor. Subsequently, I placed the files in a new folder called ckeditor within th ...

Enhancing Vue.js Scripts with Laravel Localization Language-Strings

Within my vue.js script, I have successfully implemented a sweetalert using two Laravel localization language strings. Now, I am attempting to utilize the same language strings as data properties in another vue.js component script. The issue arises when t ...

Troubleshooting: 404 Error When Trying to Send Email with AJAX in Wordpress

In the process of creating a unique theme, I encountered an interesting challenge on my contact page. I wanted to implement an AJAX function that would allow me to send emails directly from the page itself. After conducting some research, I managed to find ...

Update the value of a td element when a select option is changed in another td element within the same table row

I have a table set up as follows: Header1 | Header2 | Header3 | Header 4 | Header 5 Row 1 |<span>Some Text</span> | <select></select> Row 2 Row 3 . . . . Rows generated dynamically. My objecti ...

What alternatives are there to angular scope functions?

I find angular scope functions challenging to work with due to their lack of a clear contract. They extract parameters from the scope and store results back into the scope, rather than explicitly defining function parameters and returning a result. Conside ...

Transforming a massive JSON object into a Blob concerns directly converting it into an ArrayBuffer or Blob to prevent exceeding the maximum string length error

Situation: Within my application, I am encountering the following code: let blob = new Blob([JSON.stringify(json)], {type: "application/json"}); This code sometimes fails because the maximum string length allowed in Chrome is approximately 500M ...

The issue with JQGrid: Inaccurate selection of drop down value when edit type is set to 'select'

I am currently using JQGrid 4.4.4 and have encountered an issue with a column set to edittype = 'select'. While the value displayed in the grid row is correct, the drop-down or combo-box value is being set to the wrong value when editing the row. ...

Generate a new entry and its linked data simultaneously

The Issue: Picture this scenario: I have two connected models, Library which has multiple Books: var Library = sequelize.define('Library', { title: Sequelize.STRING, description: Sequelize.TEXT, address: Sequelize.STRING }); var Boo ...

Need help fixing the npm run watch error in Laravel/Vue?

While attempting to execute an npm run watch command in the console, I encountered a specific error message. Here is the error that was displayed × Mix Compiled with some errors in 50.24ms ERROR in ./resources/js/app.js 9:0-28 Module not found: Error: C ...

JavaScript: Retrieving the names of children within a <div> element

Within my structure setup, there is a tower div with inner elements like this: <div class="tower"> <div class="E0">abc</div> <div class="GU">123</di </div> The challenge I am facing is that I need to access the in ...

What is the method to conceal a certain element in jQuery based on the value of another element?

I am dealing with the following HTML structure: <button id="hideToggle">show/hide</button> <form id="item"> <div>Item 1 <input name="item1" type="number"/></div> <div>Item 2 <input name="item2" type="nu ...

WebGL annotations failing to display on the webpage

I'm currently working on displaying a 3D model using Three.js in a web browser and looking to incorporate annotations like the ones shown in this Sketchfab model: Interactive 3D Test. I came across a helpful guide at this link, but I'm facing iss ...