Different techniques to access values in a JSON array without relying on specific index positions

After making a request to an API, I received a JSON array with various attributes. One of the attributes is "State" and my task is to extract all the "EventName"(s) where State: "PR". The user will select the state from a dropdown menu.

In order to achieve this, I want to avoid using index numbers to access each attribute individually in the array. Instead, I am looking for a more efficient way to gather all the values that match the selected state (in this case, "PR").

So far, my attempt to filter out only the "EventName" values for "PR" resulted in a list of all the event names rather than just those specific to "PR". The desired outcome is to have a list 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);
  }
}

Answer №1

To achieve this, you can utilize the combination of Array.filter() and Array.map():

filtered_results = data_array.filter(item => (item.Type === "example"));
example_list = filtered_results.map(item => item.Name);

In reference to your current code snippet, there is a mistake:

if (condition_variable = "example") { ... }

It should be corrected to:

if (condition_variable === "example") { ... }

(For more details, check out MDN documentation)

Answer №2

To achieve this, you can leverage Array.filter() and Array.map() like so:

selectedEvents = event_data.filter(event => (event.State === "PR")).map(event => event.EventName)

For ensuring uniqueness, utilize a Set:

selectedEvents = [...new Set(event_data.filter(event => (event.State === "PR")).map(event => event.EventName))]

Answer №3

Innovative Approach

let finalList = [];
const data = [{ Name: 'Item1', Category: 'A' }, { Name: 'Item2', Category: 'B' }];
for (let idx = 0; idx < data.length; idx += 1) {
  let item = data[idx];
  if (item.Category === 'A') {
    finalList.push(item.Name);
  }
}
console.log(finalList);

Revolutionary Method

const dataList = [{ Name: 'Item1', Category: 'A' }, { Name: 'Item2', Category: 'B' }];
const filteredList = dataList.filter((f) => {
  return f.Category &&
    f.Category === 'A';
}).map((m) => { return m.Name; });
console.log(filteredList);

Answer №4

To retrieve a list of events with the state as "PR," you can utilize the array.filter() function. Additionally, to extract all event IDs from the list, you can make use of the array.map() function.

var array = [
  {eventId: '1', State: 'PR'},
  {eventId: '2', State: 'AR'},
  {eventId: '3', State: 'PR'}
];

// Filter out events with State as PR
array = array.filter(function (event) {
  return event.State === "PR";
});

// Extract all eventIds into a new array
var eventIds = array.map(function (event) {
   return event.eventId
});

console.log('eventIds:', eventIds);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve only a single column with Hibernate @JoinColumn instead of the entire model object

Currently, I am using a Hibernate entity class that has a ManyToOne relationship with another model as shown below: @ManyToOne @JoinColumn(name ="`brand-id`", referencedColumnName="`id`", nullable=false, insertable = false, updatable = false) ...

Using Gson library for JSON parsing in Android application and encountering an issue

After executing a Web Service, I received a JSON response. However, when trying to convert this JSONObject (org.json.JSONObject) into a specific object using the Gson library, my application crashes unexpectedly. The error message I receive is: { "atribut ...

Acquire a JSON response from a web address by utilizing JavaScript

If you navigate to , you will find a JSON file filled with information about your current geolocation. My goal is to save this JSON data into JavaScript variables, allowing me to manipulate and extract specific fields from the file. ...

Exploring HTML5 video playback in AngularJS

When I use this code: <video id="video" class="video-js vjs-default-skin" controls width="640" height="264"> <source src="http://localhost:3000/files/public/photos/Let-her-go.mp4" type='video/mp4' /> <p class="v ...

loading a dynamic grid using Ajax with jQuery

Setting up a jquery grid on a standard webpage gridPage.html involves incorporating HTML and JavaScript code as follows: $("#gridtable").jqGrid('setGridParam', { data: [ {'type': 'aType', ...

Enter your text in the box to search for relevant results

I need assistance with a code that allows me to copy input from a text box to the Google search box using a copy button. Upon pressing the Google search box button, it should display the search results. Here is the code I have been working on: http://jsf ...

Is there a way to stop a music track from playing?

function playMusic(){ var music = new Audio('musicfile.mp3'); if (music.paused) { music.play(); } else { music.pause(); } } <input type="button" value="sound" onclick="playMusic()" ...

Match rooms using Socket.io

I am utilizing the opentok and socket.io packages in an attempt to establish 2 distinct "groups". Successfully, I have managed to pair up individual users in a 1-to-1 relationship. However, my goal is to create two separate groups of users. For instance, ...

Creating a JSON representation of a many-to-many model in Django

I am working with a Django model that includes a Rule class and a Module class. The Rule class has attributes such as name, user, threshold, alert_value, and is_internal. While the Module class has attributes like name, description, is_internal, and rules ...

Ways to avoid browser refresh when uploading files in React applications

I'm working with a simple file upload form in React using hooks. import React, { useState } from 'react'; import { FlexContainer } from '@styles/FlexContainer'; const TestUpload = () => { const [file, setFile] = useState<F ...

Ways to assign values to array elements using their respective indices

How can I efficiently initialize elements of a C++ array with their indices in a more elegant way? Currently, my code involves manually listing out each index like so: static constexpr size_t ELEMENT_COUNT = 8; MyObject x[ELEMENT_COUNT] = {{0}, {1}, {2}, { ...

Difficulty encountered when trying to parse a URL with the fromJSON() function in R using jsonlite

I've been encountering an issue with parsing JSON content from a specific website's API using the fromJSON() function in the jsonlite package. The code works flawlessly on my personal computer but fails to identify the URL correctly when run on m ...

Incorporating promises with ajax to enhance functionality in change events

Consider the scenario where you trigger an ajax request upon a change event in the following manner: MyClass.prototype.bindChangeEvent = function(){ $(document).on('change', '#elementid', function(){ var $element = $(this); $ ...

Lunar - incorporate route parameter into DOM query_operation

Is there a way to take a route parameter and use it to trigger a click event on a DOM element? The issue is that onBeforeAction is called before the DOM is fully loaded. Any suggestions on how to solve this problem? JS onBeforeAction: function(){ var ...

The presence of the If Statement is non-existent

I'm currently working on a program that takes array inputs from the user and separates the odd elements to the front of the array and the even elements to the end. For example, if the user enters 1 for the first element, 2 for the second, and 3 for th ...

Getting a blank request body error while receiving data from an Angular 4 application in Express

My express route is indicating that the body of the request being sent is empty, according to req.body. The main node file looks like this - var express = require('express'); var bluebird = require('bluebird') const bodyParser = requ ...

What is the best way to streamline this using Javascript or jQuery?

Looking for a way to simplify the code for 4 vertical sliding panels? Check out the following script: $(".sliding-panels").click(function() { var n = $(this).attr("number"); var panels = $(".panel"); panels.not(".panel" + n).removeClass("pa ...

Is it possible for a user to change the data stored in sessionStorage variables?

Incorporating client-side JavaScript into my project to save certain variables using Web Storage - specifically, the sessionStorage. However, uncertainty exists regarding whether a user holds the capability to alter these variable values. If this is indee ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...