我有一个包含对象和数组的嵌套数据结构。我如何提取信息,即访问一个特定的或多个值(或键)?

例如:

var data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

我如何访问项目中的第二个项目的名称?


当前回答

你需要做的非常简单,它可以通过递归来实现:

const json_object = {
        "item1":{
            "name": "apple",
            "value": 2,
        },
        "item2":{
            "name": "pear",
            "value": 4,
        },
        "item3":{
            "name": "mango",
            "value": 3,
            "prices": {
                "1": "9$",
                "2": "59$",
                "3": "1$"
            }
        }
    }
    
    function walkJson(json_object){
        for(obj in json_object){
            if(typeof json_object[obj] === 'string'){
                console.log(`${obj}=>${json_object[obj]}`);
            }else{
                console.log(`${obj}=>${json_object[obj]}`);
                walkJson(json_object[obj]);
            }
        }           
    }
    
    walkJson(json_object);

其他回答

// const path = 'info.value[0].item'
// const obj = { info: { value: [ { item: 'it works!' } ], randominfo: 3 }  }
// getValue(path, obj)

export const getValue = ( path , obj) => {
  const newPath = path.replace(/\]/g, "")
  const arrayPath = newPath.split(/[\[\.]+/) || newPath;

  const final = arrayPath.reduce( (obj, k) => obj ?  obj[k] : obj, obj)
  return final;
}

jQuery的grep函数允许你过滤数组:

var data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; $.grep(data.items, function(item) { if (item.id === 2) { console.log(item.id); //console id of item console.log(item.name); //console name of item console.log(item); //console item object return item; //returns item object } }); // Object {id: 2, name: "bar"} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

python式、递归式和函数式方法来分解任意JSON树:

handlers = {
    list:  iterate,
    dict:  delve,
    str:   emit_li,
    float: emit_li,
}

def emit_li(stuff, strong=False):
    emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
    print(emission % stuff)

def iterate(a_list):
    print('<ul>')
    map(unravel, a_list)
    print('</ul>')

def delve(a_dict):
    print('<ul>')
    for key, value in a_dict.items():
        emit_li(key, strong=True)
        unravel(value)
    print('</ul>')

def unravel(structure):
    h = handlers[type(structure)]
    return h(structure)

unravel(data)

其中data是python列表(从JSON文本字符串解析而来):

data = [
    {'data': {'customKey1': 'customValue1',
           'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
  'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
               'viewport': {'northeast': {'lat': 37.4508789,
                                          'lng': -122.0446721},
                            'southwest': {'lat': 37.3567599,
                                          'lng': -122.1178619}}},
  'name': 'Mountain View',
  'scope': 'GOOGLE',
  'types': ['locality', 'political']}
]

老问题,但没有人提到lodash(只是下划线)。

如果你已经在你的项目中使用lodash,我认为在一个复杂的例子中有一种优雅的方法:

选择1

_.get(response, ['output', 'fund', 'data', '0', 'children', '0', 'group', 'myValue'], '')

一样:

选择2

response.output.fund.data[0].children[0].group.myValue

第一个选项和第二个选项之间的区别是,在Opt 1中,如果你在路径中缺少一个属性(未定义),你不会得到错误,它会返回第三个参数。

对于数组过滤器,lodash有_.find(),但我宁愿使用常规的filter()。但我仍然认为上面的方法_.get()在处理非常复杂的数据时非常有用。我在过去遇到过非常复杂的api,它很方便!

我希望它能对那些正在寻找操作标题所暗示的真正复杂数据的选项的人有用。

你需要做的非常简单,它可以通过递归来实现:

const json_object = {
        "item1":{
            "name": "apple",
            "value": 2,
        },
        "item2":{
            "name": "pear",
            "value": 4,
        },
        "item3":{
            "name": "mango",
            "value": 3,
            "prices": {
                "1": "9$",
                "2": "59$",
                "3": "1$"
            }
        }
    }
    
    function walkJson(json_object){
        for(obj in json_object){
            if(typeof json_object[obj] === 'string'){
                console.log(`${obj}=>${json_object[obj]}`);
            }else{
                console.log(`${obj}=>${json_object[obj]}`);
                walkJson(json_object[obj]);
            }
        }           
    }
    
    walkJson(json_object);