Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to slice an object?

Tags:

javascript

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"};
like image 1000
erosman Avatar asked Mar 16 '23 21:03

erosman


2 Answers

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.

like image 188
FK82 Avatar answered Mar 29 '23 19:03

FK82


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));    
like image 37
Artjom B. Avatar answered Mar 29 '23 19:03

Artjom B.