1

I would like to assign pagination result from response.data to Vue data
so the obvious way is simply

    this.data = response.data.data
    this.total = response.data.total
    this.perPage = response.data.per_page

But is there an ES6 way to assign the result directly to something like this?

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

Note: the above code doesn't work.

csum
  • 1,782
  • 13
  • 15
Anurat Chapanond
  • 2,837
  • 3
  • 18
  • 31

2 Answers2

2

Not with this - this can't be reassigned.

If the data object contains only those properties, and you changed the per_page property of the response.data to perPage, then you could use Object.assign:

Object.assign(this, response.data);

If the data object contains other properties, or you can't rename per_page, then:

const { data, total, per_page : perPage } = response.data
Object.assign(this, { data, total, perPage });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Object.assign is nice, is there anyway we can do this with spread operator? just to make sure. – Anurat Chapanond Mar 23 '20 at 04:41
  • 1
    Only if you had one or two properties of `.data` to *exclude*. Otherwise, it wouldn't accomplish anything that `Object.assign` doesn't take care of already. – CertainPerformance Mar 23 '20 at 04:43
  • tried that, still got "ReferenceError: assignment to undeclared variable data" – Anurat Chapanond Mar 23 '20 at 04:48
  • I did have "const page = ..." and then "Object.assign(this, page)", is there anywhere else? – Anurat Chapanond Mar 23 '20 at 04:58
  • 1
    Have to remove the `page =` part, otherwise `= { data, total, per_page : perPage } =` will try to assign to already existing variables named `data`, `total`, `perPage`. Destructure into standalone variables instead, then put those together into an object when passing to `Object.assign` – CertainPerformance Mar 23 '20 at 05:01
  • Yes, thank you, from here https://stackoverflow.com/questions/17781472/how-to-get-a-subset-of-a-javascript-objects-properties. Turned out it's pretty complex thing to do. – Anurat Chapanond Mar 23 '20 at 05:05
  • I understand now why you have to make another object in the assign function. Thank you. – Anurat Chapanond Mar 23 '20 at 05:30
0

So from @CertainPerformance's answer and looking into how to retrieve subset properties of an object from How to get a subset of a javascript object's properties

I got a working solution with object destructuring.

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

However the code is not shortened or easier to read, so I go back to the obvious way.

Anurat Chapanond
  • 2,837
  • 3
  • 18
  • 31