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

例如:

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

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


当前回答

这个问题很老了,所以作为当代的更新。随着ES2015的开始,有了其他方法来获取你需要的数据。现在有一个被称为对象解构的特性,用于访问嵌套对象。

Const data = { 42岁的代码: 项目:[{ id: 1、 名称:“foo” }, { id: 2 名称:“酒吧” }) }; const { 项目:[,{ 名称:secondName }) } =数据; console.log (secondName);

上面的例子从名为items的数组的name键创建了一个名为secondName的变量,该数组表示跳过数组中的第一个对象。

值得注意的是,对于这个例子来说,它可能有点过头了,因为简单的数组访问更容易阅读,但在一般情况下,它在分解对象时很有用。

这是对您的特定用例的非常简短的介绍,解构可能是一种不寻常的语法,首先要习惯。我建议阅读Mozilla的解构赋值文档来了解更多信息。

其他回答

如果你愿意包含一个库,使用JSONPath将是最灵活的解决方案之一: https://github.com/s3u/JSONPath(节点和浏览器)

对于你的用例,json路径是:

$..items[1].name

so:

var secondName = jsonPath.eval(data, "$..items[1].name");

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']}
]
// 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;
}

如果你试图通过id或名称从示例结构中访问一个项,而不知道它在数组中的位置,最简单的方法是使用underscore.js库:

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

_.find(data.items, function(item) {
  return item.id === 2;
});
// Object {id: 2, name: "bar"}

根据我的经验,使用高阶函数而不是for或for..in循环会导致代码更容易推理,因此更易于维护。

这只是我的个人意见。

如果你正在寻找一个或多个符合特定条件的对象,你可以使用query-js进行一些选择

//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1 
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});

还有一个single和一个singleOrDefault,它们的工作类似于firstand firstordefault。唯一的区别是,如果找到了不止一根火柴,他们就会扔。

关于query-js的进一步解释可以从这篇文章开始