function KeyMapValue (label, modalRs) {
// 返回对象则排序错乱,key为数字字符串时会自动排序
// 对象自动排序, 错乱1
// return _.reduce(modalRs, (pre, cur) => {
// console.log(pre, cur)
// if(_.has(label, cur)) {
// // _.set(pre, cur, _.get(label, cur))
// return pre
// }
// }, {})
// let r = _.filter(label, (v, k) => modalRs.includes(k)) // 错乱2
// let r = _.filter(label, (v, k) => _.includes(modalRs, k)) // 错乱3
// return r
// 使用symbol固定key 答案1
// let get = _.partial(_.get, label)
// return _.map(modalRs, v => {
// return { [Symbol.for(v)] : get(v) }
// })
// 返回对象数组 答案2
// return _.map(modalRs, v => {
// return {[v]: label[v]}
// })
// 返回前缀key+数字字符串 答案3
let prefix = '_'
let labelHas = _.partial(_.has, label)
let labelGet = _.partial(_.get, label)
return _.reduce(modalRs, (pre, cur) => {
let hasKey = _.memoize(_.cond([
[labelHas, _.constant(_.set(pre, prefix + cur, labelGet(cur)))]
]))
hasKey(cur)
return pre
}, {})
// 最优解是使用map,key值唯一不重复,不乱排 答案4
return _.reduce(modalRs, (pre, cur) => {
let hasKey = _.memoize(_.cond([
[labelHas, _.constant(pre.set(cur, labelGet(cur)))]
]))
hasKey(cur)
return pre
}, new Map())
}
// let rs = _.at(label, modalRs) // 只能拿到value x不符合要求
// let rs = _.pick(label, modalRs) // key会错乱0
let rs = KeyMapValue(label, modalRs)
js-排序-对象key自动排序问题
于 2022-10-18 09:02:28 首次发布