如何使用lodash的_.get方法测试多条路径?

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

使用以下 JSON 对象,如何在 lodash 的一个 _.get 方法中为每个下拉列表传递“datapath” 属性?

JSON

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

例如,这是我现在拥有的,它只包含 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 };
};

如何更好地编写上述代码,以便我可以在同一个 get 方法中为所有 3 个下拉菜单传递数据路径?

使用以下代码将您的 JSON 对象转换为 JSON 数组。

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

并将 newData 传递给您的方法,您可以在其中使用任何循环来简单地完成您的工作