How can I slice an object in Javascript?

前端 未结 10 2258
青春惊慌失措
青春惊慌失措 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 03:47

    You can reduce the result of Object.keys function

    const myObject = {
     0: 'zero',
     1: 'one',
     2: 'two',
     3: 'three',
     4: 'four'
    };
    
    const sliced = Object.keys(myObject).slice(0, 2).reduce((result, key) => {
                        result[key] = myObject[key];
    
                        return result;
                    }, {});
    
    console.log(sliced);

提交回复
热议问题