使用lodash检索嵌套元素值

问题描述 投票:0回答:3

我试图使用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"
        }]
   };

你能帮忙吗?提前致谢

javascript lodash
3个回答
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>

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)
}

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')}`);
© www.soinside.com 2019 - 2024. All rights reserved.