javascript - jQuery 数据列表

标签 javascript jquery

我有一系列可编辑的列表,按下按钮即可将其转换为某种数据结构。当它变成某种数据时,我需要将重复项添加在一起。

例子:

  • 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/

相关文章:

javascript - 在 jquery 中禁用绑定(bind)的点击事件

javascript - 如何在iframe中显示用户输入

javascript - 文件类型的输入标签的文件属性是什么?

javascript - 如何使用变量作为字段键获取 Meteor 集合字段值

javascript - jquery 工作但语法错误

javascript - Chrome 扩展使用 jQuery 获取本地 json

javascript - 数据表:How to control the <th> width of table .我正在使用Jquery -1.9.4版本

javascript - Ember - 按多个方向的多个属性对数组进行排序

jQuery 背景位置动画

javascript - 获取客户的一些身份信息