jobsys-mpower
Version:
Enhanced component based on Taro & NutUI
134 lines (118 loc) • 3.04 kB
JavaScript
import { find, reduce } from "lodash-es"
/**
* 从 options 中根据 value 获取 text
* @param value
* @param options
* @return {*|string|string}
*/
export function useTextFromOptionsValue(value, options) {
if (!options) {
return ""
}
const option = options.find((option) => option.value === value)
return option ? option.text : ""
}
/**
* 从嵌套的 options 中根据 value 获取 text, 如 [1, 3] => ["东", "南"]
*
* @param {Array} options - 嵌套的选项
* @param {Array} values - 需要查找的值
* @param {Object} [adapter={value: "value",label: "label",children: "children"}] - 选项适配器
* @return Array
*/
export function useFindTextsInValues(options, values, adapter) {
adapter = adapter || {
value: "value",
label: "text",
children: "children",
}
const labels = []
function recursiveSearch(node) {
if (values.includes(node[adapter.value])) {
labels.push(node[adapter.label])
}
if (node[adapter.children]?.length) {
node[adapter.children].forEach((child) => {
recursiveSearch(child)
})
}
}
options.forEach((item) => {
recursiveSearch(item)
})
return labels
}
/**
* 从嵌套的 options 中根据 value 获取 label
* @param {Array} options
* @param {Array} path
* @param {Object} [adapter]
* @return {*}
*/
export function useFindLabelsFromPath(options, path, adapter) {
adapter = adapter || {
value: "value",
label: "text",
children: "children",
}
let labels = []
reduce(
path,
(acc, value) => {
const item = find(acc, { [adapter.value]: value })
if (item) {
labels.push(item[adapter.label])
return item[adapter.children]
}
},
options,
)
return labels
}
/**
* [移动端适配]
* 从嵌套的 options 中根据 value 获取 text
* @param {Array} options
* @param {Array} path
* @param {Object} [adapter]
* @return {*}
*/
export function useFindTextsFromPath(options, path, adapter) {
adapter = adapter || {
value: "value",
label: "text",
children: "children",
}
return useFindLabelsFromPath(options, path, adapter)
}
/**
* 从嵌套的 options 中根据 value 获取整个 values 路径, 如地区路径: 440113 => [440000, 440100, 440113]
* @param options
* @param value
* @param adapter
* @return {*}
*/
export function useFindParentValues(options, value, adapter) {
adapter = adapter || {
value: "value",
label: "text",
children: "children",
}
const values = []
function findParentValues(options, value, values) {
for (const option of options) {
if (option[adapter.value] === value) {
values.unshift(option[adapter.value])
break
} else if (option[adapter.children]) {
const childResult = findParentValues(option[adapter.children], value, values)
if (childResult.length > 0) {
values.unshift(option[adapter.value])
break
}
}
}
return values
}
return findParentValues(options, value, values)
}