简体   繁体   中英

how to use destructuring on an array with an offset number

I have an array of objects which are dynamic data from a CMS. I want to be able to split them based on an offset number. I tried using destructuring but got an error the way I was using it.

uncaught SyntaxError: rest element must be last element

I first tried this simple setup where I could separate the last item from the firstItems but I found out you can't use destructuring like this.

const cmsData = [{..},{..},{..},{..}]
const arr = [...firstItems, last] = cmsData

What I'm trying to do is have a function where I can pass it an offset value so it would give me the first items up to the offset number and then last would be the the offset number items. for example.

const offset = 2;
const cmsData = [{..},{..},{..},{..}]
firstItems = [{..},{..}];
last = [{..},{..}];

If offset = 3 the last would be the last 3.

You can use Array.slice() with a negative offset :

 const offset = 3; const cmsData = [1, 2, 3, 4]; const firstItems = cmsData.slice(0, -offset); const lastItems = cmsData.slice(-offset); console.log(firstItems); console.log(lastItems); 

Just use Array.prototype.slice :

firstItems = cmsData.slice(0, cmsData.length - offset);
last = cmsData.slice(cmsData.length - offset);

You can only use that sort of syntax at the end of an array - it doesn't work at the beginning, as you can see. Use .slice instead:

 const cmsData = [0, 1, 2, 3]; const firstItems = cmsData.slice(0, cmsData.length - 1); const last = cmsData[cmsData.length - 1]; console.log(firstItems); console.log(last); 

Or, to get multiple items from the end:

 const cmsData = [0, 1, 2, 3]; const offset = 2; const firstItems = cmsData.slice(0, cmsData.length - offset); const last = cmsData.slice(cmsData.length - offset); console.log(firstItems); console.log(last); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM