4

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"};
erosman
  • 5,971
  • 6
  • 24
  • 41
  • 1
    `Object.key` turn it into an array ... – Neta Meta Mar 02 '15 at 10:41
  • [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) – Hacketo Mar 02 '15 at 10:41
  • 10
    How would you define 'first' two properties? Javascript objects' properties do not have any inherent order. http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Jozef Legény Mar 02 '15 at 10:41
  • I vote to close this because this is already correctly answered in@JozefLegény comment **and** in the already posted answer. – F. Hauri Mar 02 '15 at 10:57

4 Answers4

4

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.

FK82
  • 4,747
  • 4
  • 26
  • 40
2

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));    
isherwood
  • 52,576
  • 15
  • 105
  • 143
Artjom B.
  • 59,901
  • 24
  • 121
  • 211
1

you can use var newObj = Object.entries(obj).slice(0, 1)

Nando
  • 428
  • 6
  • 13
0

var obj = {a:"one", b:"two", c:"three", d:"four"};
    delete obj['d'];
    console.info(obj)
    
  /*
  sorry i forgot to put quote around d property name
   o/p
   [object Object] {
  a: "one",
  b: "two",
  c: "three"
}
  */
Waseem Bepari
  • 326
  • 2
  • 9