将多个键与单个值匹配的最简洁的方法?

The most concise way to match multiple key to a single value?

将多个键与 1 个值匹配的最简洁的方法是什么?例如在 jQuery 验证我有类似的东西:

$("#myform").validate({
  rules: {
    firstname: "required",
    middlename: "required",
    lastname: "required"
  },
  messages: {
    firstname: "Please fill in first name",
    middlename: "Please fill in middle name",
    lastname: "Please fill in last name"
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.js"></script>


<form id="myform">
  <div>
    <label for="firstname">First Name</label>
    <input type="text" id="firstname" name="firstname">
  </div>
  <div>
    <label for="middlename">Middle Name</label>
    <input type="text" id="middlename" name="middlename">
  </div>
  <div>
    <label for="lastname">Last Name</label>
    <input type="text" id="lastname" name="lastname">
  </div>
  <input type="submit" value="Search">
</form>

这很好,但我觉得重复 firstname: "required"middlename: "required"lastname: "required" 是没有必要的,我怎么可能像这样让多个键匹配相同的值?

var names = {firstname, middlename, lastname};
$("#myform").validate({
  rules: {
    names: "required"
  },
  messages: {
    firstname: "Please fill in first name",
    middlename: "Please fill in middle name",
    lastname: "Please fill in last name"
  }
});

我知道我可以使用 for 循环,但我正在寻找最简洁的方法。

我自己想出了一个解决方案 $.each(),它基本上是用相同的值匹配不同的键。

var rule = "required",
    message = "Please fill in this field",
    fields = ["firstname", "middlename", "lastname"],
    rules = {},
    messages = {};

// assign "required" to each key of fields 
$.each(fields, function (index, value) {
  rules[value] = rule;
  messages[value] = message;
});

$("#myform").validate({
  rules: rules,
  messages: messages
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.js"></script>

<form id="myform">
  <div>
    <label for="firstname">First Name</label>
    <input type="text" id="firstname" name="firstname">
  </div>
  <div>
    <label for="middlename">Middle Name</label>
    <input type="text" id="middlename" name="middlename">
  </div>
  <div>
    <label for="lastname">Last Name</label>
    <input type="text" id="lastname" name="lastname">
  </div>
  <input type="submit" value="Search">
</form>