Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access JSON array values without using index

I have made a request to an API that is returning a JSON array like this:

enter image description here

My end goal is to take the attribute "State" and find all the "EventName" (s) where State: "PR" (or another state. I am getting the State input from a user dropdown) and put that into a list.

I know I can use the index (Ex: event_data[0].State returns "PR") to get the individual attributes but how can I avoid using the index to get all the State value (or EventName values) in the entire Array? Or is that even wise? I have tried the below, but it seemed to just grab all of the EventName values rather than just those for "PR". The expected output should be a list of event names for just "PR" like pr_list = ["Debby 2000", "Dean 2001", "Jeane 2004" ... "Maria 2017"];

pr_list = [];
for (i = 0; i < event_data.length; i++) {
  state_data = event_data[i].State;
  if (state_data = "PR") {
    console.log(event_data[i].EventName)
    pr_list.append(event_data[i].EventName);
  }
}
like image 770
gwydion93 Avatar asked Jul 20 '26 19:07

gwydion93


1 Answers

You could use Array.filter() and Array.map() for this:

filtered_events = event_data.filter(event => (event.State === "PR"));
pr_list = filtered_events.map(event => event.EventName);

Regarding your existing code - you have a typo:

if (state_data = "PR") { ... }

should be:

if (state_data === "PR") { ... }

(more info on MDN)

like image 83
MTCoster Avatar answered Jul 23 '26 11:07

MTCoster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!