Open 02020 opened 3 years ago
/**
* 根据items中的值,提取values中的数据,返回对象
* @format
* @param { Array } items ["name", "age","sex"]
* @param { Object } values {name: "", age: 12, sex: 1, level:2 }
* @return { Object } { name: '', age: 12, sex: 1 }
*/
const reduce = (items: Array<any>, values: Array<any>) => {
if (Array.isArray(items) && items.length) {
return {};
}
return items.reduce((initial, current) => {
initial[current] = values[current];
return initial;
}, {});
};
// key,items
// 根据关键字将数组转换成对象
/**
*
* @param list [ { key: 'l', name: '林', value: 22 },
{ key: 'w', name: '王', value: 12 } ]
* @param key key
* @param value value
* @return { Object } { l: 22, w: 12 }
*/
function arrayToObject(list: Array<any>, key = 'key', value = 'value') {
if (!Array.isArray(list)) {
return {};
}
return list.reduce((initial, o) => {
initial[o[key]] = o[value];
return initial;
}, {});
}
/**
* 结合 map, foreach 使用更优雅
* @param {*} keys [原, 新]:['value', 'a->aa', ['b', 'bb']]
* @example
const obj = { a: 1, b: 2, c: 2, value: 11 }
const keys = ['value', 'a->aa', ['b', 'bb']]
pick(keys)(obj); // { value: 11, aa: 1, bb: 2 }
*/
export const pick = (keys: Array<any>) => (obj: Array<any>) =>
keys.reduce((acc, curr) => {
let k1, k2;
if (isString(curr)) {
const k12 = curr.split('->');
if (k12.length > 2) console.error('值异常:' + curr);
[k1, k2] = k12;
k2 = k2 || k1;
} else if (Array.isArray(curr) && curr.length === 2) {
[k1, k2] = curr;
}
isKey(obj, k1);
acc[k2] = obj[k1];
return acc;
}, {});
// demo
const obj = { a: 1, b: 2, c: 2, value: 11 };
pick(['value', 'a->aa', ['b', 'bb']])(obj);
// { value: 11, aa: 1, bb: 2 }
// parisKeyValue
/**
* 数据转换成键值对
*/
const pairsFromKeyList = (arr, keyList) => {
const l = keyList.length;
if (arr[0].length !== l) {
console.error('键值不匹配');
}
return arr.map((x) => {
let item = {};
for (let index = 0; index < l; index++) {
item[keyList[index]] = x[index];
}
return item;
});
};
// demo
var tools = [
['TOOL_SQ', '拾取'],
['TOOL_HZ', '绘制'],
];
pairsFromKeyList(tools, ['id', 'name']);
// [ { id: 'TOOL_SQ', name: '拾取' }, { id: 'TOOL_HZ', name: '绘制' } ]