如何将列表中存储的数据推送到嵌套在对象中的特定数组(“items:[]”)?
var obj = {
name: customerName,
items: [],
price: [] }
<ul>
<li>Blah blah blah<li>
</ul>
答案 0 :(得分:3)
obj.items.push(1);
obj.price.push(2);
将导致:
{
name: 'someName',
items: [ 1 ],
price: [ 2 ]
}
要将列表项中的数据推送到items
数组,您可以执行以下操作:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>jQuery list</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<script>
$(document).ready(function () {
var obj = {
items: []
};
$('li').each(function () {
// Extract the text node from the list item.
var textNode = $(this).text();
obj.items.push(textNode);
});
console.log(obj.items); // [ "one", "two", "three" ]
});
</script>
</body>
</html>