简体   繁体   中英

Angular2 linq style property accessor

Often, we are presented with an array (IEnumerable) property that specific values need to be extracted. in c# we can do something similar to:

public AssetModel PromoImage {
        get
        {
            return Assets.FirstOrDefault(x => x.AssetTypeCd == "promoimage");
        }
        private set { }
    }

Is there a way to easily to this within Angular 2?

Lodash provides similar functionality to LINQ for JavaScript programs (and then some), though not deferred execution -- LINQ queries are deferred until they are enumerated, while lodash (usually) performs the query immediately and returns an array/object of results. (Though in this case LINQ wouldn't even defer it since FirstOrDefault returns a scalar and not a queryable/enumerable.)

In your case, you would do something like this:

let obj = {
    get promoImage() {
        return _.find(assets, a => a.assetTypeCd === 'promoimage');
    },

    // ...
};

Then accessing obj.promoImage will execute the function to obtain the attribute's value.

(Here I assume this is where we are creating the new object, and assets is the assets list in the lexical scope of the constructor function. You can change it to reference this if you are storing data on the object itself and not in constructor upvalues.)


Notes:

  • Lodash does not depend on Angular at all.
  • ES6 provides a find() method on the Array prototype, so this feature will be built-in to browsers once ES6 is adopted. Sadly, IE is (as usual) the outlier without any support for it. However, Lodash is still a very useful library to have in your toolkit, and note that Lodash's find() works on objects too, not just arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM