I have a json that is like the following:
[
{"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"}
]
I currently parse it with JSON.parse and use it efficiently. What I’d like to do now is the following.
I have a variable whose value is "fullcalendar" (can be any of the "nome" in the json). I want to look for that in the array and return "fullcalendar.php" that is the value of another property of this object.
How do I do it? I am trying to understand if I can do it with filter but don’t see how to implement it. Any suggestion?
>Solution :
You can use the find() method instead of filter() to find the object with a specific value for the "nome" property in your JSON array. Here’s an example:
const jsonArray = [
// Your JSON array here...
];
const searchTerm = "fullcalendar";
const foundObject = jsonArray.find(obj => obj.nome === searchTerm);
if (foundObject) {
const url = foundObject.url;
console.log(url); // "fullcalendar.php"
} else {
console.log("Object not found in the array.");
}
In this example, the find() method is used to search for the first object in the jsonArray that has a "nome" property equal to the searchTerm. If a matching object is found, the value of its "url" property is returned. Otherwise, a message indicating that the object was not found is logged.
Using find() is a more efficient choice than filter() in this case because it stops searching as soon as the first matching object is found, rather than iterating over the entire array.