我有一系列可编辑的列表,按下按钮即可将其转换为某种数据结构。当它变成某种数据时,我需要将重复项添加在一起。
例子:
- 200克香蕉
- 100克苹果
- 200克苹果
应该变成某种数据列表,最后应该是这样的:
- 200克香蕉
- 300克苹果
这是我的尝试:
//button click event
$(".calculate").bind("click", function(e)
{
//get the correct parent of the button
var parent = $(this).closest("#calc");
//get relevant data
parent.find(".options").each(function(index, element)
{
var opt1 = $(this).children(".opt1").children("input").val(); //weight
var opt2 = $(this).children(".opt2").children("input").val(); //ingredient
});
});
基本上我单击按钮,上面的脚本找到所有相关数据。
如何将其转换为多维数组或可在其中搜索重复项的对象列表?
当我尝试制作一个动态对象时,它似乎失败了,当我制作一个多维数组进行搜索时,我被 inArray 无法搜索它们所阻止。
问题回顾: 我能够毫无问题地获取用户数据。将它变成一个列表并将重复项加在一起是问题所在。
最佳答案
我会建议你有一个包含摘要的全局对象,它看起来像这样:
$(".calculate").bind("click", function(e)
{
var fruits = {};
//get the correct parent of the button
var parent = $(this).closest("#calc");
//get relevant data
parent.find(".options").each(function(index, element)
{
var opt1 = $(this).children(".opt1").children("input").val(); //weight
var opt2 = $(this).children(".opt2").children("input").val(); //ingredient
// here is my code
if(fruits[opt2] == undefined) {
fruits[opt2] = opt1;
} else {
// assuming that opt1 is an integer
fruits[opt2] += opt1;
}
});
// use fruits variable here
});
关于javascript - jQuery 数据列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11522777/