How can I slice an object in Javascript?

前端 未结 10 2089
青春惊慌失措
青春惊慌失措 2020-12-29 03:05

I was trying to slice an object using Array.prototype, but it returns an empty array, is there any method to slice objects besides passing arguments or is just my code that

相关标签:
10条回答
  • 2020-12-29 04:02

    You don't mention it in your question, but that looks awfully a lot like an arguments object.

    Convert it to an array using Array.from() then use it like any other array. As long as it is an enumerable object.

    For a polyfill for older browsers, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

    0 讨论(0)
  • 2020-12-29 04:03

    The best modern solution to this is the combination of Object.fromEntries and Object.entries.

    const foo = {
        one: 'ONE',
        two: 'TWO',
        three: 'THRE',
        four: 'FOUR',
    }
    
    const sliced = Object.fromEntries(
        Object.entries(foo).slice(1, 3)
    )
    
    console.log(sliced)

    0 讨论(0)
  • 2020-12-29 04:09
    var obj = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four'};
    var result = Object.keys(obj).slice(0,2).map(key => ({[key]:obj[key]}));
    
    console.log(result);
    

    [ { '0': 'zero' }, { '1': 'one' } ]

    0 讨论(0)
  • 2020-12-29 04:11

    You can't unless it has a [Symbol.iterator] generator function and length property exists. Such as;

    var my_object = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', length:5 },
           sliced;
    
    my_object[Symbol.iterator] = function* (){
                                              var oks = Object.keys(this);
                                              for (var key of oks) yield this[key];
                                             };
    
    sliced = Array.prototype.slice.call(my_object, 2);
    console.log(sliced);

    0 讨论(0)
提交回复
热议问题