How can I slice an object in Javascript?
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'}] ]
You can reduce
the result of Object.keys
function
const myObject = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four'
};
const sliced = Object.keys(myObject).slice(0, 2).reduce((result, key) => {
result[key] = myObject[key];
return result;
}, {});
console.log(sliced);