简体   繁体   中英

How to test multiple paths using the _.get method of lodash?

Using the following JSON object, how can I pass the " datapath " property for each of the dropdown within just one _.get method of lodash?

JSON

"dropdownList": {
  "dropdown1": {
    "text":"Disaster",
    "datapath":"data.disaster"    
  },
  "dropdown2": {
    "text":"Process",
    "datapath":"data.process"    
  },
  "dropdown3": {
    "text":"Subqueue",
    "datapath":"data.subqueue"    
  }
}

for example, this is what I have right now which only contains the datapath for dropdown1:

const mapStateToProps = (state, ownProps) => {
  let data = _.get(state, ownProps.dropdownList.dropdown1.datapath);
  if (data == null) {
    data = _.get(state, "common." + ownProps.dropdownList.dropdown1.datapath);
  }
  let options = _.get(
    state,
    ownProps.dropdownList.dropdown1.datapathRead,
    _.get(state, "common." + ownProps.dropdownList.dropdown1.datapathRead, {
      key: "key",
      value: "value",
      text: "text",
    })
  );
  return { data: data, datapathOptions: options };
};

How can I write the above code better so that I can pass the datapath for for all 3 dropdowns in the same get method?

Convert your JSON Object to JSON array using the below code.

const newData = [...ownProps.dropdownList];

and pass newData to your method where you can use any loop to do your work simple

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