compressing object hierarchies in JavaScript

前端 未结 3 1578
抹茶落季
抹茶落季 2021-02-06 01:14

Is there a generic approach to \"compressing\" nested objects to a single level:

var myObj = {
    a: \"hello\",
    b: {
        c: \"world\"
    }
}

compress(         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 01:53

    Here's a quick CoffeeScript version based off Matthew Crumley's answer (I didn't use includePrototype as I had no need for it):

    flatten = (obj, into = {}, prefix = '', sep = '_') ->
      for own key, prop of obj
        if typeof prop is 'object' and prop not instanceof Date and prop not instanceof RegExp
          flatten prop, into, prefix + key + sep, sep
        else
          into[prefix + key] = prop
      into
    

    And a basic unflatten version, which would undoubtedly fail with repeated separators and other such trickiness:

    unflatten = (obj, into = {}, sep = '_') ->
      for own key, prop of obj
        subKeys = key.split sep
        sub = into
        sub = (sub[subKey] or= {}) for subKey in subKeys[...-1]
        sub[subKeys.pop()] = prop
      into
    

    FWIW, I use these functions to push object graphs into Redis hashes, which only support a single depth of key/value pairs.

提交回复
热议问题