admin管理员组

文章数量:1305031

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"};

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"};
Share Improve this question edited Mar 2, 2015 at 12:14 erosman asked Mar 2, 2015 at 10:40 erosmanerosman 7,7717 gold badges33 silver badges57 bronze badges 4
  • 1 Object.key turn it into an array ... – Neta Meta Commented Mar 2, 2015 at 10:41
  • Object.keys – Hacketo Commented Mar 2, 2015 at 10:41
  • 10 How would you define 'first' two properties? Javascript objects' properties do not have any inherent order. stackoverflow./questions/5525795/… – Jozef Legény Commented Mar 2, 2015 at 10:41
  • I vote to close this because this is already correctly answered in@JozefLegény ment and in the already posted answer. – F. Hauri - Give Up GitHub Commented Mar 2, 2015 at 10:57
Add a ment  | 

4 Answers 4

Reset to default 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.

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 ments:

> 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));    

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

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"
}
  */

本文标签: javascriptIs it possible to slice an objectStack Overflow