代码之家  ›  专栏  ›  技术社区  ›  Excel Hero

getPathValue()函数,用于具有数组和压缩JSON的深层对象

  •  2
  • Excel Hero  · 技术社区  · 6 年前

    背景请参考以下问题: Access deep object member of embeded JSON

    这里提供的解决方案与包含在键值中的打包JSON非常有效。

    但是,它们不处理JSON具有数组的情况。

    我在另一个问题中引用的原始函数确实处理了数组,但它不会处理打包的JSON。

    这是原始功能:

    function getPathValue(obj, path) {
        return new Function('_', 'return _.' + path)(obj);
    }
    

    这是第一个问题的答案:

    function getValue(object, path) {
        return path
            .split('.')
            .reduce((o, k) => (typeof o === 'string' ? JSON.parse(o) : o)[k], 
    object);
    }
    

    同样,两者都很好地工作,但都不能提供完整的软件包。

    我需要一个既能解决这两个问题的解决方案,而且它必须在IE11的ES5中工作。

    以下是API返回的JSON字符串示例:

    {"id":"0001","type":"donut","name":"Cake","ppu":0.55,"batters":{"batter":[{"id":"1001","type":"Regular"},{"id":"1002","type":"Chocolate"}]},"data":"{\"domain\":\"cooking.com\",\"id\":53819390}"}
    

    我希望能够使用路径字符串查询值,例如:

    value = getPathValue(obj, 'batters.batter[2].id');
    

    value = getPathValue(obj, 'type');
    

    value = getPathValue(obj, 'data.domain');
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Nina Scholz    6 年前

    您可以替换括号,并将其余值作为键。在还原的内部,可以为未给定的对象使用默认对象。

    function getValue(object, path) {
        return path
            .replace(/\[/g, '.')
            .replace(/\]/g, '')
            .split('.')
            .reduce(function (o, k) {
                return (typeof o === 'string' ? JSON.parse(o) : (o || {}))[k];
            }, object);
    }
    var object = {"id":"0001","type":"donut","name":"Cake","ppu":0.55,"batters":{"batter":[{"id":"1001","type":"Regular"},{"id":"1002","type":"Chocolate"}]},"data":"{\"domain\":\"cooking.com\",\"id\":53819390}"},
        path = 'batters.batter[1].id';
    
    console.log(getValue(object, path));
        2
  •  0
  •   Treycos    6 年前

    下面将对每个值使用regex来完成该作业:

    const data = {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters": {
            "batter": [
                {
                    "id": "1001",
                    "type": "Regular"
                },
                {
                    "id": "1002",
                    "type": "Chocolate"
                }
            ]
        },
        "data": "{\"domain\":\"cooking.com\",\"id\":53819390}"
    }
    
    function getValue(object, path) {
        return path
            .split('.')
            .reduce(function (o, k) {
                const indexSearch = (new RegExp(/\[([0-9]*)\]/)).exec(k)
                const index = indexSearch ? indexSearch[1] : null
                k = k.replace(/\[[0-9]*\]/, '')
                const sub = (typeof o === 'string' ? JSON.parse(o) : o)[k]
                return index ? sub[index] : sub;
            }, object);
    }
    
    console.log(getValue(data, 'batters.batter[1]'))
    console.log(getValue(data, 'data.domain'))
    console.log(getValue(data, 'batters.batter[1].id'))
    推荐文章