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

例如:

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

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


当前回答

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

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

$..items[1].name

so:

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

其他回答

我不认为提问只关心一个层次的嵌套对象,所以我提出下面的演示来演示如何访问深嵌套json对象的节点。好的,让我们找到id为5的节点。

var data = { code: 42, items: [{ id: 1, name: 'aaa', items: [{ id: 3, name: 'ccc' }, { id: 4, name: 'ddd' }] }, { id: 2, name: 'bbb', items: [{ id: 5, name: 'eee' }, { id: 6, name: 'fff' }] }] }; var jsonloop = new JSONLoop(data, 'id', 'items'); jsonloop.findNodeById(data, 5, function(err, node) { if (err) { document.write(err); } else { document.write(JSON.stringify(node, null, 2)); } }); <script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>

在2020年,你可以使用@babel/plugin-proposal-optional- chains,它很容易访问对象中的嵌套值。

 const obj = {
 foo: {
   bar: {
     baz: class {
   },
  },
 },
};

const baz = new obj?.foo?.bar?.baz(); // baz instance

const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined

https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining

https://github.com/tc39/proposal-optional-chaining

我更喜欢JQuery。它更干净,更容易阅读。

$.each($.parseJSON(data), function (key, value) {
  alert(value.<propertyname>);
});

动态方法

在下面的deep(data,key)函数中,您可以使用任意键字符串-在您的情况下,items[1].name(您可以在任何级别使用数组符号[i]) -如果key无效,则返回undefined。

让深= (o, k) = > k.split (' . ') .reduce ((a、c、i) = > { 让m = c.match (/(.*?)\[(\ d *) \] /); 如果(m && a!=null && a[m[1]]!=null) return a[m[1]][+m[2]]; 返回a==null ?答:[c]; }, o); / /测试 Let key = 'items[1].name' //任意深键 Let data = { 42岁的代码: 名称:项目:[{id: 11日“foo”},{id: 22岁的名字:“酒吧”},) }; Console.log (key,'=', deep(data,key));

var ourStorage = {


"desk":    {
    "drawer": "stapler"
  },
"cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  }
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"

or

//parent.subParent.subsubParent["almost there"]["final property"]

基本上,在它下面展开的每个后代之间使用一个点,当你有由两个字符串组成的对象名称时,你必须使用["obj Name"]符号。否则,只要一个点就足够了;

来源:https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects

在此基础上,访问嵌套数组将如下所示:

var ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"

来源:https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/

另一份描述上述情况的更有用的文件: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation

通过点走访问属性:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation