Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 592
JC Garcia Avatar asked Sep 05 '16 19:09

JC Garcia


People also ask

Can you slice an object in JavaScript?

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array.

How do you slice an element in JavaScript?

JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.

How do you split an object in JavaScript?

JavaScript split() Method: String ObjectThe split() method is used to split a string object into an array of strings by breaking the string into substrings. separator: The character to separate the string. The separator itself is a string. If the separator is not present it returns the entire string.

How do you slice an object in TypeScript?

In TypeScript the slice() method returns a new array that starts with the index given by the first parameter and continuing for the number of elements given by the second parameter. The slice and concat methods let you create a new array from part of or all of an array.


1 Answers

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 using Array.prototype.slice.call()).
Here's an example:

const obj = {'prop1': 'foo', 'prop2': 'bar', 'prop3': 'baz', 'prop4': {'prop': 'buzz'}}; 

You want to slice the first two values:

Object.entries(obj).slice(0,2).map(entry => entry[1]); //["foo", "bar"] 

All of the keys?

Object.entries(obj).slice(0).map(entry => entry[0]); //["prop1", "prop2", "prop3", "prop4"] 

The last key-value pair?

Object.entries(obj).slice(-1) //[ ['prop4', {'prop': 'buzz'}] ] 
like image 139
trad Avatar answered Sep 22 '22 07:09

trad