javascript – jQuery数据列表

我有一系列可编辑的列表,按按钮应该被转换成某种数据结构.当它已经变成某种数据时,我需要将重复项添加到一起.

例:

> 200g香蕉
> 100g苹果
> 200g苹果

应该变成某种数据列表,最终应该如下所示:

> 200g香蕉
> 300g苹果

这是我的尝试:

//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
    });
});

基本上我点击按钮,上面的脚本找到所有相关的数据.

如何将其转换为多维数组或可以搜索重复项的对象列表?

当我尝试制作一个动态对象时,似乎失败了,当我创建一个多维数组来搜索时,我被asArray无法搜索到.

问题回顾:
我能够得到用户数据没有问题.将其转换成列表并将重复添加在一起是问题.

解决方法

我会建议你有一个包含摘要的全局对象,这将是这样的:
$(".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
});

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...