如何在不使用$ .grep的情况下从json字符串中删除Items

时间:2016-11-23 19:58:52

标签: javascript jquery json

我有一个购物车变量,我将购物车存放在里面。

[{"course_id":"24","doc_id":"211","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"217","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"218","doc_title":"PDF Solved Past Papers","doc_price":"500"},{"course_id":"26","doc_id":"224","doc_title":"PDF Solved Past Papers","doc_price":"595"}]

我创建了一个RemoveFromCart函数。它适用于简单的JQUERY但由于$ .grep,它在Framework 7中不起作用。有没有其他方法我可以不使用$ .grep?

这是我的功能

function removeFromCart(course_id, doc_id) {
    var x = confirm("Are you sure you want to remove this item from your cart?");
    if (x) {
        $$('#cart_body').html('');
        existing_cart = localStorage.getItem("cart");

        if (existing_cart == '') {
            existing_cart = [];
        } else {
            existing_cart = JSON.parse(existing_cart);
        }

        existing_cart = $.grep(existing_cart, function (data, index) {
            return data.doc_id != doc_id
        });

        ex_cart = JSON.stringify(existing_cart);

        localStorage.setItem('cart', ex_cart);

        existing_cart = localStorage.getItem("cart");

        if (existing_cart == '') {
            existing_cart = [];
        } else {
            existing_cart = JSON.parse(existing_cart);
        }
        if (existing_cart !== null && existing_cart.length > 0) {
            var total = '';
            $$('#cart_div').show();
            existing_cart.forEach(function (arrayItem) {
                var text = '';
                text = '<li class="item-content"><div class="item-inner"><div class="item-title">' + arrayItem.doc_title + '</div><div class="item-after">' + arrayItem.course_id + '</div><div class="item-after">' + arrayItem.doc_price + '</div><div class="item-after"><i class="icon icon-cross" onclick="removeFromCart(' + arrayItem.course_id + ',' + arrayItem.doc_id + ')"></i></div></div></li>';
                total = Number(total) + Number(arrayItem.doc_price);
                $$('#cart_body').append(text);
            });
            text = '<tr><td></td><td class="text-center"><b>Total: </b></td><td class="text-center">' + total + '</td><td></td></tr>';
            $$('#cart_body').append(text);
        } else {
            $$('#cart_div').hide();
            text = '<p>Your cart is empty.</p>';
            $$('#cart_body').append(text);
        }
    } else {
        return false;
    }
}

2 个答案:

答案 0 :(得分:3)

而不是:

$.grep(existing_cart, function ...

您可以使用:

existing_cart.filter(function ...

答案 1 :(得分:0)

var new_courses = existing_cart.map( v=> {
  if(v.doc_id != doc_id)
    return v
}).filter( v=> {return v})

// new_courses does not contain the course with doc_id

map循环遍历数组的每个成员。 filter删除未在地图中返回的成员。