JC Garcia JC Garcia - 2 months ago 18
Javascript Question

How can I slice an object in Javascript?

I was trying to slice an object using Array.prototype, but it returns an empty array, is there any method to slice objects besides passing arguments or is just my code that has something wrong? Thx!!

var my_object = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four'
};

var sliced = Array.prototype.slice.call(my_object, 4);
console.log(sliced);

Answer

I was trying to slice an object using Array.prototype, but it returns an empty array

That's because it doesn't have a .length property. It will try to access it, get undefined, cast it to a number, get 0, and slice at most that many properties out of the object. To achieve the desired result, you therefore have to assign it a length, or iterator through the object manually:

var my_object = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four'};

my_object.length = 5;
console.log(Array.prototype.slice.call(my_object, 4));

var sliced = [];
for (var i=0; i<4; i++)
    sliced[i] = my_object[i];
console.log(sliced);
Comments