frenchie
frenchie

Reputation: 51927

javascript getting an array from an array in an object

I have an object MyObject and one of its properties ItemIDs is an array of ints. I want to get a new array PageItemIDs that contains only part of the ints. It's for a pager; I pass in the page number PageNumber and I get the IDs of the items on the page. Suppose the page size is 20 items.

This is what I tried. It doesn't work because js works with references so I end up changing the array of the object.

PageItemIDs = MyObject.ItemsID;
PageItemIDs = PageItemIDs.splice(PageNumber * 20, 20);

And instead of getting the ItemIDs in the page, I end up with the ItemIDs not in the page.

I know I'm not that far off but if you can help that'd be nice.

Thanks.

Edit:

When I do

PageItemIDs = PageItemIDs.slice((PageNumber -1) * 20, 20);

it works for page 1 but for every other page, it returns an empty array.

Ok, I got it, nevermind.

 PageItemIDs = PageItemIDs.slice(PageNumber * 20, PageNumber * 20);

Upvotes: 1

Views: 110

Answers (2)

Sebas
Sebas

Reputation: 21522

PageItemIDs = cloneObject(MyObject).ItemsID;
PageItemIDs = PageItemIDs.splice(PageNumber * 20, 20);

Upvotes: 1

rid
rid

Reputation: 63442

Use slice() instead of splice().

slice() returns a slice of the array, splice() changes the contents of the array in-place.

Upvotes: 1

Related Questions