用lodash检索嵌套元素值

时间:2019-04-03 18:04:22

标签: javascript lodash


我尝试使用lodash以便从JSON数组中的嵌套数组元素中检索值。
我想从特定预算中检索计划值。
即通知 TI00104 应该给我 $ 130,00

我尝试了_.filter(my_json, {budgetList: {budget: 'TI00104'}}); 但是返回的是一个空数组。

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"
        }]
   };

你们能帮忙吗? 预先感谢

3 个答案:

答案 0 :(得分:0)

您可以使用find

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"}]};
   
let op = my_json.budgetList.find(({budget}) => budget ==="TI00104")

if(op){
  console.log(op.planned)
}

答案 1 :(得分:0)

使用_.find()代替_.filter(),并使用my_json.budgetList,并使用平面对象作为谓词。使用_.get()来获取planned的值。

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>

答案 2 :(得分:0)

您可以跳过lodash并使用内置的Array.prototype.filter()

let myJson = {
  "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"
    }]
};
 
function getBudget(budgetName) {
  return myJson.budgetList.filter((b) => b.budget === budgetName)[0].planned;
}


console.log(`Budget: ${getBudget('TI00104')}`);