No one mentioned Object.entries () , which may be the most flexible way to do this. This method uses the same order as for..in when listing properties, i.e. The order in which the properties were originally entered into the object. You also get submarines with both property and value, so you can use any of them. Finally, you donβt have to worry about the properties being numerical or setting an additional length property (as with Array.prototype.slice.call() ).
Here is an example:
const obj = {'prop1': 'foo', 'prop2': 'bar', 'prop3': 'baz', 'prop4': {'prop': 'buzz'}};
You want to cut the first two values:
Object.entries(obj).slice(0,2).map(entry => entry[1]);
Any clues?
Object.entries(obj).slice(0).map(entry => entry[0]); //["prop1", "prop2", "prop3", "prop4"]
Last key-value pair?
Object.entries(obj).slice(-1) //[ ['prop4', {'prop': 'buzz'}] ]
source share