The data structure looks like:
var result={
"2":"3",
"3":{
"4":true,
"5":true
},
"8":"16",
"9":{
"19":false,
"20":true,
"21":false,
"22":false
}
}
Every item in it is a string. I want it to be in this format:
[2,3;3,4,5;8,16;9,20] or other formats are also acceptable, as long as it is This structure can
Note: Only when there are multiple parameters and the attribute is true can it be obtained
How to write using native JS? Thank you very much
伊谢尔伦2017-06-14 10:56:11
For reference
function getArr (data) {
function compare (a, b) {
return Number(a) - Number(b)
}
return Object.keys(data)
.filter(k => data[k] !== false)
.sort(compare)
.reduce((arr, k) => {
arr.push(Number(k))
var value = result[k]
if (typeof value === 'string') { arr.push(Number(value)) }
else if (typeof value === 'object' && value !== null) {
arr = arr.concat(Object.keys(value).filter(k => value[k]).sort(compare).map(k => Number(k)))
}
return arr
}, [])
}
曾经蜡笔没有小新2017-06-14 10:56:11
https://jsfiddle.net/hsfzxjy/...
function transform (data) {
let result = []
Object.keys(data)
.forEach(key => {
let values, value = data[key]
if (typeof value === 'object')
values = Object.keys(value).filter(k => value[k])
else
values = [value]
if (values.length)
result.push([key].concat(values))
})
return result
}
黄舟2017-06-14 10:56:11
JSON.stringify(result)
.replace(/"/g, '')
.replace(/}/g, ',}')
.replace(/\d+:false,/g, '')
.replace(/:true,/g, ':')
.replace(/{|}/g, '')
.replace(/:,/g, ',')
.replace(/,$/, '')
.split(',')
// [ '2:3', '3:4:5', '8:16', '9:20' ]