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

前端 未结 3 1161
走了就别回头了
走了就别回头了 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:00

    Object properties do have a certain order differing from insertion order that isn't really useful in this case as described by T.J. Crowder. This Stack Overflow question is a good read on the subject, and I recommend reading further than the first answer.

    So instead of relying on objects which have no guarantee to order1, use something that does guarantee order. You can use something like a Map, which is similar to an object with key/value pairs, but the pairs are ordered. For example:

    const obj = new Map([
        ["first", "foo"],
        ["second", "bar"],
        ["third", undefined],
        ["fourth", undefined]
    ]);
    
    const result = Array.from(obj.keys()).reduce((lastKey, currKey) => obj.get(currKey) !== undefined ? currKey : lastKey);
    
    console.log(result);

    The Map constructor takes in an iterable to create a Map out of. The array of arrays construct a Map with key and value pairs of the subarrays. Thus, the following Map is created and stored into obj:

    +----------+-----------+
    | Key      | Value     |
    +----------+-----------+
    | "first"  | "foo"     |
    | "second" | "bar"     |
    | "third"  | undefined |
    | "fourth" | undefined |
    +----------+-----------+
    

    Then, the line Array.from(obj.keys()) creates an array from the keys of the Map which are first, second, third, and fourth. It then uses Array.prototype.reduce to deduce the last key which has a defined value.

    The reduce callback uses lastKey which is the accumulator/last key with the defined value, and currKey which is the current key being processed. It then checks if obj.get(currKey) is not undefined. If it is not undefined, then it is returned and assigned to the accumulator. This goes through the entire array and the final value (accumulator) is returned to result. The result is the last key that had a defined value.2


    1It should be noted that in ES2015, there are a selection of methods that do actually guarantee returning the keys in the insertion order. These include Object.assign, Object.defineProperties, Object.getOwnPropertyNames, Object.getOwnPropertySymbols, and Reflect.ownKeys. You can rely on these, instead of using Map.

    2There are many other ways to get the last key. You could filter the array and slice it, like Reuven Chacha did. I think reducing it is more descriptive but some other approaches are more straightforward in operation.

    0 讨论(0)
  • 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).
    0 讨论(0)
  • 2021-01-29 13:20

    If you need to get the "last property with a value," you're using the wrong data structure. An object is just not a good fit. You want to use an array or a Map. I'd probably use a Map as shown by Andrew Li, since it defines a useful order and also key-based lookup.

    If you insist on using an object: Object properties do have an order as of ES2015 (aka "ES6"). That order is only enforced by certain operations; it isn't enforced by for-in or Object.keys. It is enforced by most other operations, including Object.getOwnPropertyNames (ES2015), the upcoming Object.values in the ES2017 specification, and (interestingly) JSON.stringify.

    However, the order is unlikely to be very useful to you. Assuming we're only talking about "own" properties whose names are not Symbols, the order is: Any property that's an "integer index" as defined by the specification1, in numeric order, followed by any other properties, in the order they were added to the object.

    You see why an object is the wrong structure for this: Integer indexes get priority over other properties, so given:

    const obj = { first: 'value', second: 'something', third: undefined, 42: 'value' };
    

    ...using the object's order, we'll say that the last value is 'something' when it should be 'value'. Using a Map, you'd get the right answer.

    So, I don't recommend using an object for this, but if you insist on doing so, here's how you can do it on a fully-compliant ES2015+ JavaScript engine:

    function test(testNumber, obj) {
      const last = Object.getOwnPropertyNames(obj).reduce((currentValue, key) => {
        const value = obj[key];
        return typeof value === "undefined" ? currentValue : value;
      }, undefined);
      console.log(`Test #${testNumber}: '${last}'`);
    }
    // This says 'something' (value of `second`):
    test(1, { first: 'value', second: 'something', third: undefined, fourth: undefined });
    
    // This says 'else' (value of `third`):
    test(2, { first: 'value', second: 'something', third: 'else', fourth: undefined });
    
    // This says 'something' (value of `other`):
    test(3, { any: 'value', other: 'something', thing: undefined, bla: undefined });
    
    // BUT! This says 'something' (value of `second`), not 'value' (value of `42`)!
    test(4, { first: 'value', second: 'something', third: undefined, 42: 'value' });
    .as-console-wrapper {
      max-height: 100% !important;
    }

    Note that last result.

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