filters.js
2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
* 格式化 后台 返回的 filters 数据
* @author chenxuan <xuan.chen@yoho.cn>
*/
'use strict';
const _ = require('lodash');
/**
* 处理 以风格的数据
* [
* {filter_attribute: value}
* ]
*
* 处理结果
* [
* {attribute:value,......}
* ]
*
*/
let verboseAttrHandler = (filterField, dataArr) => {
let result = [];
let re = new RegExp(`^${filterField}_`);
dataArr.forEach(obj => {
let item = {};
let keys = Object.keys(obj);
keys.forEach(key=>{
let newKey = key.replace(re, '');
item[newKey] = obj[key];
});
result.push(item);
});
return result;
};
/*
* 处理 以下风格:
* {
"340,99999": "¥339以上",
"0,149": "¥0-149",
"150,179": "¥150-179",
"180,339": "¥180-339"
* },
*
* 处理结果:
* [
* {id: '0,149', value: '0,149', name: '¥0-149'},
* {id: '150, 179', value: '150,179', name: '¥150-179'}
* .....
* ]
* 按照字符串顺序
*/
let keyIdHandler = (filterField, obj) => {
const result = [];
const keys = Object.keys(obj);
keys.sort();
keys.forEach(key=> {
let item = {};
item.id = key;
let t = obj[key];
let isObject = Object.prototype.toString.apply(t) === '[object Object]';
if (isObject) {
item = Object.assign(item, t);
} else {
item.name = t;
}
result.push(item);
});
return result;
};
function prettyFilter(filters) {
let keys = _.keys(filters);
_.forEach(keys, key => {
let process;
// 相同规律的 使用 相同的处理规则
switch (key) {
case 'color':
case 'size':
case 'brand':
case 'style':
process = verboseAttrHandler;
break;
case 'gender':
case 'priceRange':
case 'discount':
process = keyIdHandler;
break;
// 其他不做处理
default:
process = _.noop;
}
filters[key] = process(key, filters[key]) || filters[key];
});
}
module.exports = prettyFilter;
/*
filter Object经过 prettyFilter, camelCase 后的 数据格式:
{
color: [{id,name,value, code}],
gender: [{id,name}],
size: [id,name],
discount: [{id,name,count}],
priceRange: [{id, name}],
ageLevel: [{id,name, productCount}]
brand: [{id, name,domain,alif,ico,keyword,hotKeyword,isHot, nameEn, nameCn}]
groupSort,
}
*/