首页 > 解决方案 > 格式化 JSON 的最佳方式

问题描述

我已经获得了一些数据(如下所示的随机示例),我想将其格式化为以下格式(示例与随机示例不同,但格式相同): 编辑:

格式和示例中的数字不代表彼此。

export const formatted = [
    {date: "hone: 30},
    {date: "20/6,
  ];

我只能想到在循环中使用 map() 效率低下。但是有没有更好的方法来自动进行这种过滤?

export const unformatted = [
        {_string: "20t: 1,
               00000,
                    doc_cs: {
                        value: 1902
                    }
                }
            ]
            }

这只是一个学习经验,我只想学习并提供如何在 JS React 中正确格式化给定数据的布局。

标签: jsx

解决方案


One reduce and one find seem to do it. I defined cars/phones as separate objects to speed this up. Let me know if this helps. It should not be very difficult to get them same result from the array form you posted. Let me know if things will get you going or I missed something.

var cars = {
	key: "car",
	doc_count: 26,
	sales_over_time: {
		buckets: [
			{
				key_as_string: "2018-07-20",
				key: 1532088000000,
				doc_count: 1,
				total_sales: {
					value: 3850
				}
			},
			{
				key_as_string: "2018-07-21",
				key: 1532174400000,
				doc_count: 1,
				total_sales: {
					value: 260
				}
			},
			{
				key_as_string: "2018-07-22",
				key: 1532260800000,
				doc_count: 3,
				total_sales: {
					value: 0
				}
			},
			{
				key_as_string: "2018-07-23",
				key: 1532347200000,
				doc_count: 1,
				total_sales: {
					value: 933
				}
			},
			{
				key_as_string: "2018-07-24",
				key: 1532433600000,
				doc_count: 2,
				total_sales: {
					value: 1902
				}
			}
		]
	}
};
var phones = {
	key: "phone",
	doc_count: 26,
	sales_over_time: {
		buckets: [
			{
				key_as_string: "2018-07-20",
				key: 1532088000000,
				doc_count: 1,
				total_sales: {
					value: 4678
				}
			},
			{
				key_as_string: "2018-07-21",
				key: 1532174400000,
				doc_count: 1,
				total_sales: {
					value: 2445
				}
			},
			{
				key_as_string: "2018-07-22",
				key: 1532260800000,
				doc_count: 3,
				total_sales: {
					value: 833
				}
			},
			{
				key_as_string: "2018-07-23",
				key: 1532347200000,
				doc_count: 1,
				total_sales: {
					value: 139
				}
			},
			{
				key_as_string: "2018-07-24",
				key: 1532433600000,
				doc_count: 2,
				total_sales: {
					value: 1102
				}
			}
		]
	}
}

var result = cars.sales_over_time.buckets.reduce((result, value, index, array) => {	
  var phoneObj = phones.sales_over_time.buckets.find(phone => phone.key === value.key)
	result.push({
	date: value.key_as_string,
	car: value.total_sales.value,
	phone: phoneObj ? phoneObj.total_sales.value : 'N/A',
})
	return result
}, [])

console.log(result)


推荐阅读