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);
That's because it doesn't have a
.length
property. It will try to access it, getundefined
, cast it to a number, get0
, and slice at most that many properties out of the object. To achieve the desired result, you therefore have to assign it alength
, or iterator through the object manually:You can
reduce
the result ofObject.keys
functionTry adding a 'length' property to
my_object
and then your code should work:Nobody mentioned Object.entries() yet, which might be the most flexible way to do it. This method uses the same ordering as
for..in
when enumerating properties, i.e. the order that properties were originally entered in the object. You also get subarrays with both property and value so you can use whichever or both. Finally you don't have to worry about the properties being numerical or setting an extra length property (as you do when usingArray.prototype.slice.call()
).Here's an example:
You want to slice the first two values:
All of the keys?
The last key-value pair?