如何获取存储在localStorage中的JSON对象的长度?

时间:2019-05-04 06:02:07

标签: arrays json reactjs local-storage

我有一个REACT JS应用,其中JSON对象 CartObj 以以下格式存储在localStorage中:

{
        "Master Automotives": [
            {
                "SparePartID": "43",
                "Name": "Oil and Lubricants",
                "Price": "4500",
                "VendorID": "48",
                "CompanyName": "Master Automotives",
                 "Qty": 1,
                 "TotalPrice": "4500"

            },
            {
                "SparePartID": "45",
                "Name": "Lights",
                "Price": "2300",
                "VendorID": "48",
                "CompanyName": "Master Automotives",
                 "Qty": 1,
                 "TotalPrice": "2300"
            }
        ],

        "Repair Solutions": [
            {
                "SparePartID": "47",
                "Name": "Steering Wheel",
                "Price": "1500",
                "VendorID": "60",
                "CompanyName": "Repair Solutions",
                 "Qty": 1,
                 "TotalPrice": "1500"
            }
        ],
        

         "FiveStar Automotives": [
            {
                "SparePartID": "51",
                "Name": "Brakes",
                "Price": "234",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives",
                 "Qty": 1,
                 "TotalPrice": "234"
            },
            {
                "SparePartID": "53",
                "Name": "Clutch",
                "Price": "999",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives",
                 "Qty": 1,
                 "TotalPrice": "999"
            },
              {
                "SparePartID": "55",
                "Name": "LED",
                "Price": "288",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives",
                 "Qty": 1,
                 "TotalPrice": "288"
            }
        ]
    
}

我想获取 JSON对象上方的长度,该长度存储在我的 localStorage 中,作为“ CartObj ”。如我们所见,以上数据总共有 6(六个)个不同的产品,因此我希望长度等于6。

我使用了下面的代码,但它具有非常强的 ,例如23876:

const lenObj = JSON.stringify(localStorage.getItem('storeObj'));
        const len = lenObj.length;
        console.log("JSON obj length: ",len);

帮助,我如何以正确的方式获取此 JSON 对象的长度。

3 个答案:

答案 0 :(得分:2)

localStorage.getItem返回一个字符串,因此您必须使用JSON.parse而不是 JSON.stringfy

还有一件事,即您的json不是单个数组,它包含多个数组,如果要计算所有长度,则应该迭代对象。

这是解决方案。

const lenObj = JSON.parse(localStorage.getItem('storeObj'));
var count = 0;
for(var item in lenObj) {
   count += lenObj[item].length
}
console.log("JSON obj length: ",count);

答案 1 :(得分:1)

使用此:

const cartLength = Object.values(JSON.parse(localStorage.getItem('storeObj'))).flat().length;

或一行:

var handler = StripeCheckout.configure({
            billingAddress: true,
            opened: function() {
                jQuery('.wp-travel-form-field.button-field').find('.wt-icon.wt-icon-spinner').remove();
            },
            closed: function() {
                jQuery('.wp-travel-form-field.button-field').find('.wt-icon.wt-icon-spinner').remove();
            },
            currency: cart_data.currency,
            key: wp_travel.payment.stripe_publishable_key,
            panelLabel: 'Pay' + " {{amount}}",
            shippingAddress: true,
            token: function(token, args) {
                var gateway = $("input[name='wp_travel_payment_gateway']:checked").val();
                var mode = $('[name=wp_travel_payment_mode]').attr('value');
                var title = $('.entry-title').html() || 'Trip Book';
                var description = $('#overview').find('p').html() || 'Trip Description';

                if (!mode) {
                    mode = 'full';
                }
                $('.stripe-spin').show();
                // Use the token to create the charge with a server-side script.
                // Ajax POST
                $.ajax({
                    cache: false,
                    crossDomain: true,
                    data: {
                        token: token,
                        args: args,
                        action: 'stripe_charge',

                        gateway: gateway,
                        mode: mode,
                        // currency: currency,
                        title: title,
                        description: description,
                        total: cart_data.amount,
                        // partial: partial
                    },
                    type: "POST",
                    url: wp_travel.ajaxUrl,
                    success: function(msg) {
                        if (msg.status) {
                            response = msg.charge;
                            complete(response);
                        }
                    }

                    // Done - check for errors - empty cart if success
                }).done(function(data, status, xhr) {

                    // Fail - add message
                }).fail(function(xhr, status, error) {

                    // Porbably nothing required here
                }).always(function(data, status, error) {
                    $('.stripe-spin').show();
                    // Debug

                });
            }

        });

答案 2 :(得分:0)

您可以使用Object.values

function getLength(obj) {
  return (Object.values(obj)).flat().length

}

console.log(getLength(obj)); // => 6

const obj = {
	'Master Automotives': [
		{
			SparePartID: '43',
			Name: 'Oil and Lubricants',
			Price: '4500',
			VendorID: '48',
			CompanyName: 'Master Automotives',
			Qty: 1,
			TotalPrice: '4500',
		},
		{
			SparePartID: '45',
			Name: 'Lights',
			Price: '2300',
			VendorID: '48',
			CompanyName: 'Master Automotives',
			Qty: 1,
			TotalPrice: '2300',
		},
	],

	'Repair Solutions': [
		{
			SparePartID: '47',
			Name: 'Steering Wheel',
			Price: '1500',
			VendorID: '60',
			CompanyName: 'Repair Solutions',
			Qty: 1,
			TotalPrice: '1500',
		},
	],

	'FiveStar Automotives': [
		{
			SparePartID: '51',
			Name: 'Brakes',
			Price: '234',
			VendorID: '70',
			CompanyName: 'FiveStar Automotives',
			Qty: 1,
			TotalPrice: '234',
		},
		{
			SparePartID: '53',
			Name: 'Clutch',
			Price: '999',
			VendorID: '70',
			CompanyName: 'FiveStar Automotives',
			Qty: 1,
			TotalPrice: '999',
		},
		{
			SparePartID: '55',
			Name: 'LED',
			Price: '288',
			VendorID: '70',
			CompanyName: 'FiveStar Automotives',
			Qty: 1,
			TotalPrice: '288',
		},
	],
};

function getLength(obj) {
  return (Object.values(obj)).flat().length

}

console.log(getLength(obj));