猿问

使用 getJson 解析树

我有一个包含订单数据的 JSON 文件。JSON 文件的格式如下:


{

  "orders": [

    {"name": "Peter", "email": "peter@aol.com"}


    {"name": "David", "email": "david@aol.com"}


    { "name": "George", "email": "george@aol.com"}

  ]

}

如你看到的; 所有数据都是被调用的分支的一部分,"orders"然后每个订单都是它自己的分支,但该分支没有名称。


我正在尝试生成"name"数据集中的s列表。


使用简化的数据集,我会执行以下操作:


$(data).each(function(i, name){

    $('#namesText').append($("li")

        .append($("li").append(name.name))

  });

})

然而,这不起作用,因为数据不在树的第一级。


我的问题是,当级别没有名称时,我如何降低级别?


拉莫斯之舞
浏览 156回答 3
3回答

慕桂英546537

这听起来像是一个 DFS 问题,其中每个对象都有可能是原始数据类型或另一个对象的键。由于该name字段可以在您需要解决的给定约束中的任何级别,我会说使用 DFS 算法,它遍历对象中的每个键,如果有另一个对象,请查看它直到找到一个name字段。更好的解决方案是重新设计数据结构,这样您就可以保证随时知道该name字段的级别和位置。

慕桂英4014372

尝试namesText.innerHTML=&nbsp;data.orders.map(p=>`<li>${escape(p.name)}</li>`).join``var data = {&nbsp; "orders": [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "name": "Peter",&nbsp; &nbsp; &nbsp; "email": "peter@aol.com",&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "name": "David",&nbsp; &nbsp; &nbsp; "email": "david@aol.com",&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "name": "George",&nbsp; &nbsp; &nbsp; "email": "george@aol.com",&nbsp; &nbsp; }&nbsp; ]}namesText.innerHTML= data.orders.map(p=>`<li>${escape(p.name)}</li>`).join``<ul id="namesText"></ul>

斯蒂芬大帝

如果您想要name来自orders数组元素的属性列表,您可以使用Array.map:const&nbsp;names&nbsp;=&nbsp;myJson.orders.map(o&nbsp;=>&nbsp;o.name);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答