gpt4 book ai didi

jquery - 创建具有动态值的 json 对象

转载 作者:行者123 更新时间:2023-12-01 08:38:02 24 4
gpt4 key购买 nike

我正在尝试使用复选框列表的值创建一个 JSON 对象。

对象的关键属性应该是复选框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}

我应该怎么做才能获得所需的输出?

最佳答案

您可以使用 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>

关于jquery - 创建具有动态值的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51239920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com