Fai*_*ong 2 arrays hash jquery object
我有一个任务需要从输入值转换为格式对象数组,如下所示:
[{
id: 1,
worker_id: 2,
status:1
},{
id: 2,
worker_id: 2,
status: 1
},{
id: 3,
worker_id: 2,
status:1
}]
Run Code Online (Sandbox Code Playgroud)
我的输入有多行。
<!-- row1 -->
<input type="text" id="id" value="1"/>
<input type="text" id="worker_id" value="2"/>
<input type="text" id="status" value="1"/>
<!-- row2 -->
<input type="text" id="id" value="2"/>
<input type="text" id="worker_id" value="2"/>
<input type="text" id="status" value="1"/>
<!-- row3 -->
<input type="text" id="id" value="2"/>
<input type="text" id="worker_id" value="2"/>
<input type="text" id="status" value="1"/>
<input type="submit" value="submit" />
Run Code Online (Sandbox Code Playgroud)
我怎样才能在 jQuery 中做到这一点?感谢您的任何帮助!
更新
单击按钮提交后,此格式可以传递到文本字段吗?
[[1,2,1],[2,2,1],[3,2,1]]
Run Code Online (Sandbox Code Playgroud)
如果您可以构建 HTML 来分隔各组(例如input
使用元素),那么您可以使用它来创建所需的输出。div
map()
另请注意,id
属性在页面内必须是唯一的。在您的情况下,您可以使用data*
属性来存储给定元素的标识符input
。尝试这个:
var arr = $('div').map(function() {
var o = {};
$(this).find('input').each(function() {
o[$(this).data('id')] = this.value;
});
return o;
}).get();
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" data-id="id" value="1" />
<input type="text" data-id="worker_id" value="2" />
<input type="text" data-id="status" value="1" />
</div>
<div>
<input type="text" data-id="id" value="2" />
<input type="text" data-id="worker_id" value="2" />
<input type="text" data-id="status" value="1" />
</div>
<div>
<input type="text" data-id="id" value="2" />
<input type="text" id="worker_id" value="2" />
<input type="text" data-id="status" value="1" />
</div>
Run Code Online (Sandbox Code Playgroud)
update ( [{1,2,1},{2,2,1},{3,2,1}]
) 中的输出格式是不可能的,因为对象必须具有键和值。相反,您可以使用多维数组。您可以修改上述内容来执行此操作:
var arr = $('div').map(function() {
return [$(this).find('input').map(function() {
return this.value;
}).get()]
}).get();
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" data-id="id" value="1" />
<input type="text" data-id="worker_id" value="2" />
<input type="text" data-id="status" value="1" />
</div>
<div>
<input type="text" data-id="id" value="2" />
<input type="text" data-id="worker_id" value="2" />
<input type="text" data-id="status" value="1" />
</div>
<div>
<input type="text" data-id="id" value="2" />
<input type="text" data-id="worker_id" value="2" />
<input type="text" data-id="status" value="1" />
</div>
Run Code Online (Sandbox Code Playgroud)