How can I slice an object in Javascript?

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

    Nobody mentioned Object.entries() yet, which might be the most flexible way to do it. This method uses the same ordering as for..in when enumerating properties, i.e. the order that properties were originally entered in the object. You also get subarrays with both property and value so you can use whichever or both. Finally you don't have to worry about the properties being numerical or setting an extra length property (as you do when using Array.prototype.slice.call()).
    Here's an example:

    const obj = {'prop1': 'foo', 'prop2': 'bar', 'prop3': 'baz', 'prop4': {'prop': 'buzz'}};
    

    You want to slice the first two values:

    Object.entries(obj).slice(0,2).map(entry => entry[1]);
    //["foo", "bar"]
    

    All of the keys?

    Object.entries(obj).slice(0).map(entry => entry[0]);
    //["prop1", "prop2", "prop3", "prop4"]
    

    The last key-value pair?

    Object.entries(obj).slice(-1)
    //[ ['prop4', {'prop': 'buzz'}] ]
    

提交回复
热议问题