我尝试了几个不同的答案,但最终导致控制台错误或覆盖现有数据。
var item = {};
var items = [];
$('li').each(function() {
var itemName = $(this).find('.name').text();
var itemData = $(this).find('.data').text();
//for(var i = 0, lens = items.length; i < 1; i++) {
// if(items[i].name === itemName) {
// ?
// }
//}
item = {
name: itemName,
data: itemData
}
items.push(item);
});
&#13;
<li>
<span class="name">Item 1</span>
<span class="data">3</span>
</li>
<li>
<span class="name">Item 1</span>
<span class="data">6</span>
</li>
<li>
<span class="name">Item 1</span>
<span class="data">9</span>
</li>
<li>
<span class="name">Item 2</span>
<span class="data">3</span>
</li>
<li>
<span class="name">Item 2</span>
<span class="data">6</span>
</li>
&#13;
答案 0 :(得分:2)
此代码将实现您的目标:
var items = {};
$('li').each(function() {
var itemName = $(this).find('.name').text();
var itemData = $(this).find('.data').text();
items[itemName] = items[itemName] || [];
items[itemName].push(itemData);
});
var result = Object.keys(items).map(function(name) {
return {name: name, data: items[name]};
});
console.log(result);
更新1 :(添加其他媒体资源)
var items = {};
$('li').each(function() {
var itemName = $(this).find('.name').text();
var itemData = $(this).find('.data').text();
items[itemName] = items[itemName] || {name: itemName};
//Add data
items[itemName].data = items[itemName].data || [];
items[itemName].data.push(itemData);
//Add other property
items[itemName].time = Date.now();
});
var result = Object.keys(items).map(function(name) {
return items[name];
});
<强>演示:强>
var item = {};
var items = {};
$('li').each(function() {
var itemName = $(this).find('.name').text();
var itemData = $(this).find('.data').text();
items[itemName] = items[itemName] || [];
items[itemName].push(itemData);
});
var result = Object.keys(items).map(function(name) {
return {name: name, data: items[name]};
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li>
<span class="name">Item 1</span>
<span class="data">3</span>
</li>
<li>
<span class="name">Item 1</span>
<span class="data">6</span>
</li>
<li>
<span class="name">Item 1</span>
<span class="data">9</span>
</li>
<li>
<span class="name">Item 2</span>
<span class="data">3</span>
</li>
<li>
<span class="name">Item 2</span>
<span class="data">6</span>
</li>
答案 1 :(得分:1)
var item = {};
var items = [];
$('li').each(function () {
var itemName = $(this).find('.name').text();
var itemData = $(this).find('.data').text();
var add_new = true;
for(var i = 0, lens = items.length; i < lens; i++) {
if(items[i].name === itemName) {
items[i].data.push(itemData);
add_new = false;
}
}
if (add_new) {
item = {
name: itemName,
data: [itemData]
}
items.push(item);
}
});
console.log(items);