javascript - How to turn such an object into an array or a specified object format?
phpcn_u1582
phpcn_u1582 2017-06-14 10:54:11
0
3
738

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

phpcn_u1582
phpcn_u1582

reply all(3)
伊谢尔伦

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
    }, [])
}
曾经蜡笔没有小新

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
}
黄舟
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' ]

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template