Search code examples
javascriptlodash

Retrieve nested element value with lodash



I am trying to use lodash in order to retrieve a value from a nested array element in an Array of JSON.
I want to retrieve the planned value from a specific budget.
I.e. Informing TI00104 should give me $ 130,00

I tried _.filter(my_json, {budgetList: {budget: 'TI00104'}}); but the return was an empty array.

var my_json = {  
    "department":"TI",
    "fiscal_year":"2019",
    "expense":"Vehicle Rent",
    "expense_description":"Credit Card payment",
    "user_cc":"2150",
    "accounting_account":"34101022",
    "budgetList":[  
        {  
            "budget":"TI00104",
            "planned":"$ 130,00"
        },
        {  
            "budget":"TI00105",
            "planned":"$ 140,00"
        }]
   };

Could you guys help? Thanks in advance


Solution

  • Use _.find() instead of _.filter(), and it my_json.budgetList, and use a flat object as the predicate. Use _.get() to get the planned value.

    var my_json = {"department":"TI","fiscal_year":"2019","expense":"Vehicle Rent","expense_description":"Credit Card payment","user_cc":"2150","accounting_account":"34101022","budgetList":[{"budget":"TI00104","planned":"$ 130,00"},{"budget":"TI00105","planned":"$ 140,00"}]};
    
    var result = _.get(
      _.find(my_json.budgetList, {budget: 'TI00104'})
    , 'planned');
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>