getPathValue()函数用于带有数组和打包JSON的深层对象 [英] getPathValue() function for deep objects with arrays and with packed JSON

查看:100
本文介绍了getPathValue()函数用于带有数组和打包JSON的深层对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关背景,请参阅以下问题:
访问嵌入JSON的深层对象成员

For background, please refer to this question: Access deep object member of embeded JSON

那里提供的解决方案与键值中包含的打包JSON一起很好地工作。

The solutions offered there worked very well with the packed JSON contained in key values.

但是,它们无法处理

我在其他问题DID中引用的原始函数处理数组,但无法处理打包的JSON。

The original function I referenced in the other question DID handle arrays, but it would not handle the packed JSON.

这是原始功能:

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

这是第一个问题的答案:

and this is the answer from the first question:

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

同样,两者都可以很好地工作,但是都不能提供整套服务。

Again, both work well, but neither offers the whole package.

我需要一个可以同时解决这两个问题的解决方案,并且必须能在IE11的ES5中正常工作。

I need a solution that will do both and it must work in IE11's ES5.

这是一个示例API返回的JSON字符串:

Here is a sample API returned JSON string:

{"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}"}

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

I'd like to be able to query values with a path string, for example:

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

value = getPathValue(obj, 'type');

value = getPathValue(obj, 'data.domain');


推荐答案

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

You could replace the brackets and take the remaining values as keys. Inside of the reducing, you could use a default object for not given objects.

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));

这篇关于getPathValue()函数用于带有数组和打包JSON的深层对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆