代码之家  ›  专栏  ›  技术社区  ›  Filip

带虚线字符串键的Javascript Json对象到对象[关闭]

  •  -4
  • Filip  · 技术社区  · 6 年前

    我需要解析Json响应

    {
       "product": "office",
       "info": 
       {
          "brand": 
          [
            "1brand"
          ],
          "detail": 
          {
            "number": 
            {
                "min": 1,
                "max": 5
             },
           }
       }
    };
    

    {
        "product" : "office",
        "info.brand" : ["1brand"],
        "info.detail.number.min" : 1,
        "info.detail.number.max" : 5
    }
    

    2 回复  |  直到 6 年前
        1
  •  1
  •   Nina Scholz    6 年前

    您可以对每一层嵌套对象采用递归方法,收集键并将它们用于新对象中最后找到的值。

    function flatKeys(object) {
    
        function iter(part, keys) {
            Object.keys(part).forEach(function (k) {
                var allKeys = keys.concat(k);
                if (part[k] && !Array.isArray(part[k]) && typeof part[k] === 'object') {
                    return iter(part[k], allKeys);
                }
                flat[allKeys.join('.')] = part[k];
            });
        }
    
        var flat = {};
        iter(object, []);
        return flat;
    }
    
    var object = { product: "office", info: { brand: ["1brand"], detail: { number: { min: 1, max: 5 } } } };
    
    console.log(flatKeys(object));
        2
  •  0
  •   Nenad Vracar    6 年前

    可以使用 reduce

    let data = {"product":"office","info":{"brand":["1brand"],"detail":{"number":{"min":1,"max":5}}}}
    
    function parse(input, res = {}, prev = '') {
      return Object.keys(input).reduce((r, e) => {
        let key = prev + (prev && '.') + e, val = input[e]
        if (typeof val == "object" && !Array.isArray(val)) parse(val, res, key)
        else r[key] = input[e]
        return r;
      }, res)
    }
    
    let result = parse(data)
    console.log(result)