Similar to Array slice(), is it possible to slice an object (without looping though it properties)?
Simplified example:
var obj = {a:"one", b:"two", c:"three", d:"four"};
For example: Get the first 2 properties
var newObj = {a:"one", b:"two"};
Technically objects behave like hash tables. Therefore, there is no constant entry order and the first two entries are not constantly the same. So, this is not possible, especially not without iterating over the object's entries.
All major browsers (tested in Firefox 36, Chrome 40, Opera 27) preserve the key order in objects although this is not a given in the standard as Jozef Legény noted in the comments:
> Object.keys({a: 1, b: 2})
["a", "b"]
> Object.keys({b: 2, a: 1})
["b", "a"]
So theoretically you can slice objects using a loop:
function objSlice(obj, lastExclusive) {
var filteredKeys = Object.keys(obj).slice(0, lastExclusive);
var newObj = {};
filteredKeys.forEach(function(key){
newObj[key] = obj[key];
});
return newObj;
}
var newObj = objSlice(obj, 2);
Or for example with underscore's omit
function:
var newObj = _.omit(obj, Object.keys(obj).slice(2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With