javascript – jQuery数据列表

前端之家收集整理的这篇文章主要介绍了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
});
原文链接:https://www.f2er.com/jquery/152892.html

猜你在找的jQuery相关文章