jsx - 格式化 JSON 的最佳方式
问题描述
我已经获得了一些数据(如下所示的随机示例),我想将其格式化为以下格式(示例与随机示例不同,但格式相同): 编辑:
格式和示例中的数字不代表彼此。
export const formatted = [
{date: "hone: 30},
{date: "20/6,
];
我只能想到在循环中使用 map() 效率低下。但是有没有更好的方法来自动进行这种过滤?
export const unformatted = [
{_string: "20t: 1,
00000,
doc_cs: {
value: 1902
}
}
]
}
这只是一个学习经验,我只想学习并提供如何在 JS React 中正确格式化给定数据的布局。
解决方案
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)
推荐阅读
- ios - 带有图像集名称的 UIImage
- scala - 尝试添加 Scala Logging 依赖项时面临问题
- jquery - 如何在 Bootstrap 中将这些图像居中?
- git - Bitbucket:关系团队项目存储库
- javascript - 是否可以使用 reactjs CRA 为不同的环境渲染不同的 html
- python - 安装 Python geopandas 失败
- javascript - 在 IE11 中获取 Javascript 严重错误
- ios - 系统颜色未出现在 IBInspectable 属性中
- html-table - Safari/Retina 中奇怪的表格边框行为
- docker - docker ee windows server 2016 无法创建网络