我有一个JSON,如下所示:
[
{"id":1,"nome":"smartform","url":"smartform.php","label":"Dashboard","icon":"fas fa-th-large","data_attribute":"","parent":"Smartform"},
{"id":2,"nome":"form_wizard","url":"form_wizard.php","label":"Crea uno Smartform","icon":"fas fa-plus","data_attribute":"data-action=\"create\" data-step=\"0\" data-token=\"0\"","parent":"Smartform"},
{"id":3,"nome":"fullcalendar","url":"fullcalendar.php","label":"Calendario","icon":"far fa-calendar","data_attribute":"","parent":"Tools"},
{"id":4,"nome":"gantt","url":"gantt.php","label":"Gantt","icon":"fas fa-stream","data_attribute":"","parent":"Tools"},
{"id":5,"nome":"timesheet","url":"timesheet.php","label":"Timesheet","icon":"fas fa-hourglass","data_attribute":"","parent":"Tools"},
{"id":6,"nome":"kanban","url":"kanban.php","label":"Kanban","icon":"fas fa-list-ul","data_attribute":"","parent":"Tools"},
{"id":7,"nome":"openpoints","url":"items.php?tipo=openpoints","label":"Open Points","icon":"fas fa-keyboard","data_attribute":"","parent":"Risk Management"},
{"id":8,"nome":"risks","url":"items.php?tipo=risks","label":"Rischi","icon":"fas fa-exclamation","data_attribute":"","parent":"Risk Management"},
{"id":9,"nome":"issues","url":"items.php?tipo=issues","label":"Issue","icon":"fas fa-fire","data_attribute":"","parent":"Risk Management"},
{"id":10,"nome":"changerequests","url":"items.php?tipo=changerequests","label":"Change Requests","icon":"fas fa-plus","data_attribute":"","parent":"Risk Management"}
]
我目前使用JSON.parse
解析它并有效地使用它。我现在想做的是我有一个变量,其值为“fullcalendar”(可以是JSON中的任何“nome”)。我想在数组中查找它,并返回“fullcalendar.php”,这是该对象的另一个属性的值。
我该怎么做?我想知道我是否可以用filter
来实现它,但不知道如何实现它。有什么建议吗?
5条答案
按热度按时间yuvru6vn1#
您可以使用
find()
方法而不是filter()
来查找JSON数组中“nome”属性具有特定值的对象。下面是一个例子:在本例中,
find()
方法用于搜索jsonArray
中具有与searchTerm
相同的“nome”属性的第一个对象。如果找到匹配的对象,则返回其“url”属性的值。否则,将记录一条指示未找到对象的消息。在这种情况下,使用
find()
比filter()更有效,因为它在找到第一个匹配对象时立即停止搜索,而不是迭代整个数组。093gszye2#
使用
.find
方法返回包含fullcalendar
值的对象,然后仅打印url
属性j2qf4p5b3#
你需要使用Array.prototype.find:
pes8fvy94#
虽然可以使用find(或filter)访问单个项,但每次都需要迭代数组。这听起来像是你想通过字符串键来任意访问一个项目,它本质上是一个map/dict。在这种情况下,我建议从一个项目数组转换为由'nome'值键控的相同项目的Map。然后你可以直接访问它,而且更有效,因为对密钥的随机访问是恒定时间的。假设您在页面/应用程序的整个生命周期中的不同时间访问不同的值,这将更好地工作。
https://playcode.io/1482928
roejwanj5#
filter
你可以得到符合你在filter()函数中提供的选项的元素。你可以在这个文档中得到更多。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter[0]
如果你想从中得到一个元素,你应该通过索引切片得到第一个元素。但是你需要处理过滤数组的长度为0的情况。则[0]可能未定义。.url
您可以通过.
访问属性。