代码之家  ›  专栏  ›  技术社区  ›  Hudhaifa Yoosuf

使用动态值创建json对象

  •  1
  • Hudhaifa Yoosuf  · 技术社区  · 6 年前

    我正在尝试创建一个json对象,其中包含复选框列表的值。

    对象的关键属性应该是checkbox id,我是这样得到的。

    var elementId = $(this).attr("id");
    

    这是我的完整代码。

    var ImportParameters = [];
            $('#divImportOptions .ace').each(function (index, obj) {
                debugger;
                var elementId = $(this).attr("id");
                var elementValue = $(this).is(':checked');
                ImportParameters.push({ elementId : elementValue });                
            });
    

    我现在的输出是这样的。

    {elementId: true}
    

    我需要的输出是这样的

    { chkAllowDetailsInfo : true}
    

    我应该怎么做才能得到想要的输出?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Rory McCrossan Hsm Sharique Hasan    6 年前

    你可以用 map() 从jquery对象集合创建数组。要使用变量作为对象的键,请用大括号将其括起来, [] 以下内容:

    var importParameters = $('#divImportOptions .ace').map(function() {
      return { [this.id]: this.checked };                
    }).get();
    
    console.log(importParameters);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="divImportOptions">
      <input type="checkbox" id="foo" class="ace" value="A" checked="true" />
      <input type="checkbox" id="bar" class="ace" value="B" />
      <input type="checkbox" id="fizz" class="ace" value="C" checked= "true" />
      <input type="checkbox" id="buzz" class="ace" value="D" />
    </div>