How to get the last key of object which has a value

前端 未结 3 1206
走了就别回头了
走了就别回头了 2021-01-29 12:30

I need to get the last key of an object which has a value. So if this would be the object...

const obj = { first: \'value\', second: \'something\', third: undefi         


        
3条回答
  •  难免孤独
    2021-01-29 13:06

    Very tricky, iteration through object does not necessarily guarantees order. ES2015 provides several methods that are iterating through symbol\string type keys by following the creation order.

    Assuming last key which has a value is the last entry that was defined in the object with truthy value:

    function getLastKeyWithTruthyValue(obj) {
        Object.getOwnPropertyNames(obj).filter(key => !!obj[key]).slice(-1)[0]
    }
    
    1. Get the array of the property names in the creation order (Object.getOwnPropertyNames is supported in the most of the modern browsers, see browser compatibility)
    2. Filter out the falsy values (using filter(Boolean) can be a cool method to filter, as described in this cool answer. If any value which is not undefined is required, use val => val !== undefined as the filter callback.
    3. Get the last item in the filtered array (will return undefined in case that all values are falsy).

提交回复
热议问题