export function jsonToList(obj, inId) {
// obj是传进来的对象,inId非必传,传了的话所有对象的key 都是 inId.xxxx
const doneList = []
function eachKeyVal(object, title) {
if (object.constructor === Array) {
if (!object.length) {
doneList.push({ [title]: [] })
}
for (let index = 0; index < object.length; index++) {
const element = object[index]
if (Object.keys(element).length) {
eachKeyVal(element, title + '.' + index)
} else {
doneList.push({ [title + '.' + index]: element })
}
}
} else if (object.constructor === Object) {
if (!Object.keys(object).length) {
doneList.push({ [title]: {}})
}
for (const key in object) {
if (object.hasOwnProperty(key)) {
const element = object[key]
if (element && typeof element === 'object') {
eachKeyVal(element, (title ? (title + '.') : '') + key)
} else {
doneList.push({ [(title ? (title + '.' + key) : key)]: element })
}
}
}
}
}
eachKeyVal(obj, inId || '')
// 如果是要 { key: value},去掉map即可
return doneList.map(a => {
const key = Object.keys(a)[0]
return { key: key, value: a[key] }
})
}
// 数字转json
export function listToJson(list) {
const obj = {}
list.map(a => {
const key = a.key
const keyarr = key.split('.')
const value = a.value
let stayObj = obj
keyarr.map((b, i) => {
if (i === keyarr.length - 1) {
stayObj.constructor === Array ? stayObj.push(value) : stayObj[b] = value
} else {
if (stayObj[b] === undefined) {
stayObj[b] = keyarr[i + 1] === '0' ? [] : {}
}
stayObj = stayObj[b]
}
})
})
return obj
}
网友评论