// 对象查找 target 要查找的对像 keyStr 链式字符串 或者是数组
// findObj({a:{b:{c:1}}}, 'a.b.c')
const findObj = (target, keyStr) => {
const keys = typeof keyStr === "string" ? keyStr.split(".") : [...keyStr];
const key = keys.shift();
if (typeof target !== "object") {
return target;
}
if (target[key] !== undefined) {
if (keys.length > 0) {
return findObj(target[key], keys);
} else {
return target[key];
}
} else {
return undefined;
}
};
// 根据数组中对像中某一属性进行排序
// property 排序属性可以深层次的'a.b.c'
// asc true=升序 false=降序
// 栗子:[{a:1}].sort(objSort('a'))
const objSort = (property, asc=true) => (a,b) => {
const indexa = findObj(a, property) || 0;
const indexb = findObj(b, property) || 0;
return asc ? indexa - indexb : indexb - indexa;
};
export {
findObj,
objSort
}