Jquery how to find an Object by attribute in an Array

前端 未结 11 2106
灰色年华
灰色年华 2020-12-02 11:55

Given I have an array of \"purpose\" objects:

//array of purpose objects:
var purposeObjects = [
    {purpose: \"daily\"},
    {purpose: \"weekly\"},
    {pu         


        
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 12:46

    I have created a util service for my angular application. It have two function which use very often.

    For example you have object.

    First getting value from object recursively without throwing undefined error.

    {prop: { nestedProp1: {nestedProp2: somevalue}}}; get nestedProp2 2 without undefined checks.

    Second filter array on basis

    [{prop: { nestedProp1: {nestedProp2: somevalue1}}}, {prop: { nestedProp1: {nestedProp2: somevalue2}}}];

    Find object from array with nestedProp2=somevalue2

    app.service('UtilService', function(httpService) {
    this.mapStringKeyVal = function(map, field) {
        var lastIdentifiedVal = null;
        var parentVal = map;
        field.split('.').forEach(function(val){
            if(parentVal[val]){
                lastIdentifiedVal = parentVal[val]; 
                parentVal = parentVal[val]; 
            }
        });
        return lastIdentifiedVal;
    }
    
    
    this.arrayPropFilter = function(array, field,value) {
        var lastIdentifiedVal = null;
        var mapStringKeyVal = this.mapStringKeyVal;
        array.forEach(function(arrayItem){
            var valueFound = mapStringKeyVal(arrayItem,field);
            if(!lastIdentifiedVal  && valueFound && valueFound==value){
                lastIdentifiedVal = arrayItem;
            }
        });
        return lastIdentifiedVal;
    }});
    

    For solution for current question. inject UtilService and call,

    UtilService.arrayPropFilter(purposeArray,'purpose','daily');
    

    Or more advanced

    UtilService.arrayPropFilter(purposeArray,'purpose.nestedProp1.nestedProp2','daily');
    

提交回复
热议问题