首页 > javascript > 如何在jquery json中增加自定义计数

如何在jquery json中增加自定义计数 (how to increase custom count in jquery json)

问题

如果笔记本电脑型号和序列ID相同,我将添加新字段totalModel并增加计数。例如,在下面的情况下:serialid“1”和笔记本电脑型号“xyz”将来两次所以我想将“totalModel”计数添加为2,依此类推。我怎样才能在jquery中实现这一点

解决方法

这个问题并不是关于jQuery,而是关于映射和过滤数组和对象。但是,我们可以使用一些jQuery便捷方法来解决它。

解决这些问题的很大一部分是通过正确定义您想要做的事情。从您的问题来看,您希望获得每个笔记本电脑型号的唯一序列ID的地图。我们可以使用JavaScript的Array.prototype.reduce来生成这样的地图(请注意,我们将为我们遇到的每个笔记本电脑型号中的第一个采用'sold'值):

var laptop_models = data.reduce(function (memo, obj) {
    if (!memo[obj.laptopModel]) {
        memo[obj.laptopModel] = {
            unique_serial_ids: [],
            sold: obj.sold
        };
    }

    if ($.inArray(obj.serialid, memo[obj.laptopModel].unique_serial_ids) === -1) {
        memo[obj.laptopModel].unique_serial_ids.push(obj.serialid);
    }

    return memo;
}, {});

接下来,我们可以将laptop_models对象映射到您指定为预期结果的数组中:

var result = $.map(laptop_models, function (laptop_model, model_name) {
    return {
        laptopModel: model_name,
        totalModel: laptop_model.unique_serial_ids.length,
        sold: laptop_model.sold
    };
});

问题

If laptop model and serial id are same, i've to add new field totalModel and increase count. For example in below case: serialid "1" and laptop model "xyz" are coming two time so i want to add "totalModel" count as 2 and so on. How can i achieve this in jquery

解决方法

This question is not really about jQuery, it is about mapping and filtering arrays and objects. However, we can use some jQuery convenience methods to solve it.

A large part of solving these problems is by properly defining what you want to do. It sounds from your question that you want to get a map of unique serial ids per laptop model type. We can use JavaScript's Array.prototype.reduce to produce just such a map (Note that we will take the 'sold' value for the first of each laptop model we encounter):

var laptop_models = data.reduce(function (memo, obj) {
    if (!memo[obj.laptopModel]) {
        memo[obj.laptopModel] = {
            unique_serial_ids: [],
            sold: obj.sold
        };
    }

    if ($.inArray(obj.serialid, memo[obj.laptopModel].unique_serial_ids) === -1) {
        memo[obj.laptopModel].unique_serial_ids.push(obj.serialid);
    }

    return memo;
}, {});

Next, we can map our laptop_models object into the array you specified as your expected result:

var result = $.map(laptop_models, function (laptop_model, model_name) {
    return {
        laptopModel: model_name,
        totalModel: laptop_model.unique_serial_ids.length,
        sold: laptop_model.sold
    };
});
相似信息